Shabbir92
Shabbir92

Reputation: 11

how to count digits of a phonenumber(included 0) in javascript?

I am trying to write a javascript , And want to count digits of a var str, in the code below var str is 6 digits (012345), but when i run this code it is showing answer 4. i tried to search on google but answer not found; how to get correct answer and fix it ?

my code

 var str = 012345;
 var x = String(str);
var n = x.length;
    document.getElementById("demo").innerHTML = "var str is[" + n + "] Digits";

Upvotes: 1

Views: 165

Answers (3)

Shrikantha Budya
Shrikantha Budya

Reputation: 644

try replacing the code with:

var str = "012345";
var n = str.length;
document.getElementById("demo").innerHTML = "var str is[" + n + "] Digits";

Upvotes: 1

Andy
Andy

Reputation: 63524

If you were to actually have a mixed letter/number string from which you wanted to get the number of digits you could use a regex. match creates an array of all the matches in the string - in this case \d, a digit (g says to check the whole of the string, not give up the search when the first digit has been found.) You can then check the length of the returned array.

'01xx2s3eg345'.match(/\d/g).length; // 7

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

Initialize you phone number as string using quotes.

var str = '0123213'

And use length property to get its length

Upvotes: 1

Related Questions