How to trim leading zeros in numbers in JavaScript

If you have a number that starts with a zero, such as 010 or 02, how do you delete the zero?

If you have a number starting with zero, for example010or02, How to delete the zero?

There are many ways.

The most explicit is to useparseInt():

parseInt(number, 10)

10 is the base, and 10 should always be specified to avoid inconsistencies between different browsers, although some engines can work without it.

Another way is to use+Unary operator:

+number

These are the simplest solutions.

You can also goRegular expressionThe route is as follows:

number.replace(/^0+/, '')

Download mine for freeJavaScript beginner's manual


More js tutorials: