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.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
MySQL: Read out values with leading zeros
Question | 4 Answers
Delphi: Add leading zeros to a number
Tip | 0 Comments
Delphi/Lazarus: Display current Date and Time
Tip | 0 Comments
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
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.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
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
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