Yaser Moradi
Yaser Moradi

Reputation: 3307

Remove first zero values from string using regex

I've created a string value using padStart method (padLeft), for example:

"5".padStart(19, "0")

which results into "0000000000000000005" How can I get that 5 back using regex? I've tested this:

/^0*(\d+)$/.exec(d)[1]

which return 5 correctly.

But this regex returns null for something like "00000012.22"

Samples:

5 > 5

005 > 5

0011.22 > 11.22 >> This is a first problem!

00100 >> 100

001001 >> 1001

00.5 >> 0.5 This is a second problem!

Working codes but without regex:

function toDb(d) {
        if (d == null) return null;
        var precisionIndex = d.indexOf('.');
        return d.toString().padStart((29 + precisionIndex + 1), '0');
        }

function fromDb(d) {
            if (d == null) return null;
            d = d.replace(/^0+/, ''); // I'd like to use regex here
            if (d.indexOf('.') == 0) // I'd like to use regex here
                d = '0' + d; // I'd like to use regex here
            return d;
    }

fromDb(toDb('0.5')) returns 0.5 for me. But I'd like to use regex in my codes.

Upvotes: 2

Views: 1993

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use String#replace method to replace leading 0.

console.log(
  "0000000000000000005".replace(/^0+(?=\d)/, '')
)

console.log(
  "000000000000000000.5".replace(/^0+(?=\d)/, '')
)

In the regex start anchor(^) assert the beginning position of the string and 0+ matches combination one or more repetition of 0, altogether ^0+ matches 0s at the beginning.

UPDATE : To avoid removing 0 just before the . use positive look ahead assertion, (?=\d) match up to the 0 which follows a digit.

Upvotes: 6

Related Questions