How to count leading zeros?

Viewed 1956

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:

id.split(/^0{1,3}/)

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.

4 Answers

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

You could have it all without any regular expression:

let somenumber = "0001";

function count_leading_zeros(some_input) {
    let splitted = some_input.split("");
    let i = 0;
    while (splitted.shift() == 0) {
        i += 1;
    }
    return i;
}

console.log(count_leading_zeros(somenumber));

String#split breaks strings into parts where regex matches the string part. Thus, the results you get are expected, 001 when split with /^0{1,3}/ (the first 1, 2 or 3 zeros) will yield an empty string (at the start of string) and 1.

You want to use a regex that always matches any number of zeros at the start of the string:

console.log('001'.match(/^0*/)[0].length); // => 2
console.log('01'.match(/^0*/)[0].length);  // => 1
console.log('1'.match(/^0*/)[0].length);   // => 0

No need to use || or any kind of safeguarding here since /^0*/ always matches, any amount of zeros (0*) at the start of the string (^).

With lodash:

_.takeWhile(str, (c) => c === '0').length
Related