I have a variable pid (represents parent_id attribute of each li element) like "1","14","253",etc. I need to align the content of li to left and right.
Based on condition, if the parent id has an even number of digits, then align left, else align right.
How can I find out the number of digits in the pid variable using Javascript?
Thanks for stopping by.
I have a variable pid (represents parent_id attribute of each li element) like "1","14","253",etc. I need to align the content of li to left and right.
Based on condition, if the parent id has an even number of digits, then align left, else align right.
How can I find out the number of digits in the pid variable using Javascript?
Thanks for stopping by.
Share Improve this question edited Jul 19, 2013 at 11:53 dda 6,2132 gold badges27 silver badges35 bronze badges asked Jul 19, 2013 at 11:47 Milind AnantwarMilind Anantwar 82.2k26 gold badges96 silver badges128 bronze badges 1-
What's wrong with
pid.length
? – Alex K. Commented Jul 19, 2013 at 11:50
4 Answers
Reset to default 5var a = '253';
alert(a.length);
Just in case your pid is not string, you will get undefined, you can use toString() to be on safer side.
Few tests:
var str1 = 253;
alert(str1.length); //will not work give undefined
var str3 = str1.toString();
alert(str3.length); // will work
var str2 = '253';
alert(str2.length); //will work
Hope this will help.
~K
To get the number of digits in numeric string in Javascript , the easiest way I can think of is use the length property of String:
var pid = "123";
var numDigits = pid.length;
if(numDigits === parseFloat(numDigits)) {
if(numDigits%2 === 0 ) {
// even
}
else {
// odd
}
}
I think you can also use length directly on a string.
var pid = "123";
pid.length;
Given that you have the variable, you can just check the length of the string representation.
The number of digits is then even if
pid.length % 2 == 0
Edit: Removed link