77 Votes

JavaScript: Remove leading zeros

Tip by NetLabel | 2012-04-12 at 20:26

Today, I have a little tip showing how you can remove all leading zeros from a string in JavaScript:

var s = '00123';

var i = Number(s);

alert(i);  // '123'

Number() converts the parameter passed into a number. Because numbers are not containing leading zeros, the zeros from the beginning of our string are dropped out automatically.

Who likes it more complicated, can also use a regular expression:

var s = '00123';

var i = s.replace(/^(0+)/g, '');

alert(i);  // '123'

Also this regular expression removes the leading zeros from a string. In our case, of course, the first solution is the easier one, but whenever we would like to delete other characters than zeros, we have to use the regular expression. Instead of "0" in "/^(0+)/g", you can simply use an other character for this.

22 Votes

The first solution only works for numbers. Using a regex has nothing to do with liking it more complex. If my string is "00035abdc" the first solution will not return the required result. Only the second solution with the regex will.
2016-01-29 at 15:49

ReplyPositive Negative
13 Votes

Yes, you should use the RegEx solution whenever other characters than numbers can occur in the string.

However, my solution was for a string with leading zeros and in this case it is working.
2016-01-29 at 16:52

Positive Negative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

PHPExcel: Leading Zeros

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.