2

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.

1
  • 1
    Actually, there is a regex to deal with that kind of tasks, but - if you want to make it really comprehensible - it will be very long and rather unweildly. Commented Feb 8, 2017 at 9:34

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

007 makes a better test string.
I really appreciated your answer + It's four time faster (-: Thanks for your details information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.