Remove/ truncate leading zeros by javascript/jquery Remove/ truncate leading zeros by javascript/jquery jquery jquery

Remove/ truncate leading zeros 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 valuealert(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); //numberx = x+"";alert(typeof x); //string

hope it helps somebody