How to trim the leading zero in a number in JavaScript
By Flavio Copes
Learn how to trim the leading zero from a number in JavaScript, using parseInt() with radix 10, the unary plus operator, or a regular expression like /^0+/.
If you have a number with a leading zero, like 010 or 02, the quickest way to remove that zero is to convert it to a number with parseInt() or the unary + operator.
A value with a leading zero is really a string. JavaScript numbers can’t store leading zeros, so '010' is what you actually have, usually coming from user input or an API.
There are various ways to trim it.
The most explicit is to use parseInt():
parseInt('010', 10) // 10
10 is the radix, and should be always specified to avoid inconsistencies across different browsers, although some engines work fine without it. Older engines treated a string starting with 0 as octal, so '010' could come back as 8. Passing 10 forces base ten everywhere.
Another way is to use the + unary operator:
+'010' // 10
This converts the string to a number, with the same result you’d get from Number('010').
Those are the simplest solutions.
When you want a string back
Both approaches above give you a number. If you need to keep the value as a string, go the regular expression route:
'010'.replace(/^0+/, '') // '10'
^0+ matches one or more zeros, but only at the start of the string. Those zeros get replaced with nothing, and the rest stays untouched. A zero in the middle, like in '102', is safe.
Pitfalls to watch out for
parseInt() stops at the decimal point, because it parses integers:
parseInt('0.5', 10) // 0
If your value can have decimals, use the + operator instead:
+'0.5' // 0.5
The regular expression has its own edge case. If the string is all zeros, everything matches and you get back an empty string:
'000'.replace(/^0+/, '') // ''
You can fix it with a lookahead that keeps the last digit:
'000'.replace(/^0+(?=\d)/, '') // '0'
(?=\d) requires a digit to follow the matched zeros, so the final zero survives.
My advice: if a number is what you need in the end, convert with parseInt() or + and skip the regular expression entirely. +'000' gives you 0 with no special cases to handle.
Related posts about js: