numeric variables in JS - javascript

For a variable x=5, how do I know it is number five or the character '5'?
Btw, in JS, do characters follow the ASCII table? Then can I manipulate a character variable. For example, if variable x is character a, can I do x=x+1 to make it character b?

To see if x is the number 5, as opposed to the string "5", you can use the identity operator:
if (x === 5) {
}
Identity will not do any implicit conversions; it will return true only if both operands are equal without any conversions.
For example, if variable x is character a, can I do x=x+1 to make it
character b?
No. x = x + 1 will convert 1 to a string, perform string concatenation and return "a1"

You can use
typeof x;
which returns a string describing the type of the variable, like number, string or object.
To get the character code of a character, use charCodeAt:
var mystring = 'a';
mystring.charCodeAt(0);
And to get a character from an augmented char code, use String.fromCharCode :
var nextLetter = String.fromCharCode( mystring.charCodeAt(0) + 1 ); // returns "b"
This creates a new string from the incremented char code from the first character in mystring.

Just get the type of the variable:
console.log(typeof '5'); // Returns 'string';
console.log(typeof 5); // Returns 'number';
As for your second question, no, it doesn't work:
console.log('b' + 1); // Returns 'b1'

To check if a variable is a number:
if (typeof x == 'number')
// x is a number
Doing this x = x + 1 when x = b, would result in the string 'a1';

If your var x is not an integer, this is the best way to change it to integer..
To change the x to integer
x = parseInt(x);
You can how add any value to the x, example:
x = x + 2;
Since we have changed the x to integer, we can now identify if this is equal to 5
if(x == 5){
//Your Codes Here
}

Related

charcode comparison against raw interger and stored value give different results

Whenever I compare a charcode from an index to a raw integer i get the proper response. When I store that same integer in a variable and use the variable to make the comparison, my result is different. Why?
var f = "What a wonderful world";
let newline = 10; //unicode doesnt work '\u000A'; //charcode (10);
let space = 32; //unicode doesn't work '\u0020' //charcode (32);
var test = f.charCodeAt(4);
console.log(test);
//returns 32
console.log("space");
//returns " 'is space'"
if (test === 32) console.log("number");
//returns "number"
if (test === space) console.log("variable");
//false

What is the meaning of this syntax exactly when finding the frequency of characters occuring in the string?

What is the meaning of this syntax exactly when finding the frequency of characters occuring in the string?
var str = 'abcccdddd';
function maxCharCount(target) {
const chars = {};
let maxChar = '';
let maxValue = 1;
for (let char of target) {
chars[char] = chars[char] + 1 || 1; //what is the meaning of this line exactly in detail???
}
return chars;
}
console.log(maxCharCount(str));
chars[char] + 1 || 1 has two sides: left and right. If left one resolves to falsy value, then the whole expression is resolved to the right side, and if the left resolves to truthy, the expression is resolved to the left side.
That said, the left side can only be falsy in one case: when chars[char] is undefined (when chars does not contain a property with name char). And undefined + 1 gives NaN i.e. not a number, which is a falsy value.
Code like this should definitely be considered as bad, because it makes a developer's intention not obvious. Instead something at least like this should be preferred:
chars[char] = chars[char] ? chars[char] + 1 : 1;
Full code and description:
function maxCharCount(target) {
const chars = {};
let maxChar = '';
let maxValue = 1;
for (let char of target) {
chars[char] = chars[char] + 1 || 1;
}
return chars;
}
console.log(maxCharCount(str));
If chars is an object, the code will go to the property within chars named whatever char is equal to. If the property exists, it will be increments by 1. If it doesn't exist, it will be created and set to 1.
What the function itself does is it takes a string of characters, and returns an object containing character counts for each character in the string - so if we passed the string hello, the output should be:
{
"h": 1,
"e": 1,
"l": 2,
"o": 1
}
If char is in obj chars then it will + 1 it's count otherwise it will add char to object with value 1.

How to add digit before first character of string in javascript?

I have a string, and I need to get its first character. if that character is alphabetic (between A to Z or a to z)then i want add any digit in-front of that character
var x = 'somestring'
alert(x.charAt(0));
in above string first character has alphabet then i need to attach any digit (0 to 9) before string
4somestring
How can I fix my code?
if (/[a-zA-Z]/.test(x.charAt(0))) {
x = (Math.floor(Math.random() * 10)) + x;
}
Simply use regexes, the test method, and Math.random.
You could also use an anchor so you don't have to call charAt:
if (/^[a-zA-Z]/.test(x)) {
Here is a fiddle.
var x = 'somestring';
if (! /^\d+$/.test(x[0]))
x = 5 + x; // or some other number

Remove/ truncate leading zeros by javascript/jquery

Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
I would use the Number() function:
var str = "00001";
str = Number(str).toString();
>> "1"
Or I would multiply my string by 1
var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
Maybe a little late, but I want to add my 2 cents.
if your string ALWAYS represents a number, with possible leading zeros, you can simply cast the string to a number by using the '+' operator.
e.g.
x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"
x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)
if your string doesn't represent a number and you only need to remove the 0's use the other solutions, but if you only need them as number, this is the shortest way.
and FYI you can do the opposite, force numbers to act as strings if you concatenate an empty string to them, like:
x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string
hope it helps somebody
Since you said "any string", I'm assuming this is a string you want to handle, too.
"00012 34 0000432 0035"
So, regex is the way to go:
var trimmed = s.replace(/\b0+/g, "");
And this will prevent loss of a "000000" value.
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
You can see a working example here
parseInt(value) or parseFloat(value)
This will work nicely.
I got this solution for truncating leading zeros(number or any string) in javascript:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
1. The most explicit is to use parseInt():
parseInt(number, 10)
2. Another way is to use the + unary operator:
+number
3. You can also go the regular expression route, like this:
number.replace(/^0+/, '')
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
You should use the "radix" parameter of the "parseInt" function :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt
parseInt('015', 10) => 15
if you don't use it, some javascript engine might use it as an octal
parseInt('015') => 0
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
const number = '0000007457841';
console.log(+number) //7457841;
OR number.replace(/^0+/, '')
Regex solution from Guffa, but leaving at least one character
"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
I wanted to remove all leading zeros for every sequence of digits in a string and to return 0 if the digit value equals to zero.
And I ended up doing so:
str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")
function removeLeadingZeros(string) {
if (string.length == 1) return string
if (string == 0) return 0
string = string.replace(/^0{1,}/, '');
return string
}
One another way without regex:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
With short string it will be more faster than regex (jsperf)
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
Use "Math.abs"
eg: Math.abs(003) = 3;
console.log(Math.abs(003))

Adding extra zeros in front of a number using jQuery?

I have file that are uploaded which are formatted like so
MR 1
MR 2
MR 100
MR 200
MR 300
ETC.
What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99
So files are formatted
MR 001
MR 010
MR 076
ETC.
Any help would be great!
Assuming you have those values stored in some strings, try this:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
pad("3", 3); // => "003"
pad("123", 3); // => "123"
pad("1234", 3); // => "1234"
var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
I have a potential solution which I guess is relevent, I posted about it here:
https://www.facebook.com/antimatterstudios/posts/10150752380719364
basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code
var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);
I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.
then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.
Note: see Update 2 if you are using latest ECMAScript...
Here a solution I liked for its simplicity from an answer to a similar question:
var n = 123
String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5); // returns 00123
UPDATE
As #RWC suggested you can wrap this of course nicely in a generic function like this:
function leftPad(value, length) {
return ('0'.repeat(length) + value).slice(-length);
}
leftPad(123, 5); // returns 00123
And for those who don't like the slice:
function leftPad(value, length) {
value = String(value);
length = length - value.length;
return ('0'.repeat(length) + value)
}
But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.
UPDATE 2
In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.
So with ES6 it became as simple as:
var n = '123';
n.padStart(5, '0'); // returns 00123
Note: #Sahbi is right, make sure you have a string otherwise calling padStart will throw a type error.
So in case the variable is or could be a number you should cast it to a string first:
String(n).padStart(5, '0');
function addLeadingZeros (n, length)
{
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
//addLeadingZeros (1, 3) = "001"
//addLeadingZeros (12, 3) = "012"
//addLeadingZeros (123, 3) = "123"
This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023
If you split on the space, you can add leading zeros using a simple function like:
function addZeros(n) {
return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}
So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.
Or as a regular expression:
function addZeros(s) {
return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}
I'm sure someone can do it with one replace, not two.
Edit - examples
alert(addZeros('MR 3')); // MR 003
alert(addZeros('MR 23')); // MR 023
alert(addZeros('MR 123')); // MR 123
alert(addZeros('foo bar 23')); // foo bar 023
It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.
Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)
function pad(str, new_length) {
('00000000000000000000000000000000000000000000000000' + str).
substr((50 + str.toString().length) - new_length, new_length)
}
I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:
function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }
Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.
var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;
}
console.log("After : \n string :"+str+"\n Length :"+str.length);
It worked for me !
To increase the zeroes, update the 'max' variable
Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:
str could be a number or a string.
formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}
Add more zeros if needs large digits
In simple terms we can written as follows,
for(var i=1;i<=31;i++)
i=(i<10) ? '0'+i : i;
//Because most of the time we need this for day, month or amount matters.
Know this is an old post, but here's another short, effective way:
edit: dur. if num isn't string, you'd add:
len -= String(num).length;
else, it's all good
function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}
Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.
var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);
By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful

Categories

Resources