How to count leading zeros?

I’m trying to make a Regex to count leading zeros on the following formats: 01, 001 and 0001.

These are some id’s that I need to process somehow.

I tried something like this:


For example, if my input is 0001, I would like to see something like this:

['0', '0', '0']

But I’m getting this:

["", "1"]

I only care about the leading zeros, and I can’t count the ones that are after the format I specified.


Use match so you can get the zeros. With that, you can read the length. If there is no match, it returns null.

var str = "0001"
var match = str.match(/^0+/)
var level = match ? match[0].length : 0

in one line

var str = "0001"
var level = (str.match(/^0+/) || [''])[0].length

Leave a Reply

Your email address will not be published. Required fields are marked *