0

I know this has been asked many times and I did find a solution, value.replace(/^([\d,]+)$|^([\d,]+)\.0*$|^([\d,]+\.[0-9]*?)0*$/, "$1$2$3").

But... I'm no regex expert so I'm just curious as to why this doesn't work /[\.0]+$/... 10 should return 10 but I just can't figure out how to exclude whole numbers that end with 0s.

1.7500, 1.1010, 1.0000, 10

1.75, 1.101, 1, 1

4
  • 1
    /[\.0]+$/ does not require the input to have a decimal point. You need to require it. Commented Mar 8, 2022 at 16:35
  • @trincot I thought by not using ? that the decimal was required? Commented Mar 8, 2022 at 17:00
  • 1
    But [\.0] leaves the choice to match with either . or with 0. So if every time (of the repeated +) it is an 0, it will still match -- without ever having matched a dot. Commented Mar 8, 2022 at 17:01
  • @trincot so following your recommendations I'm able to capture the group after the decimal with this (?<=\.) but can't do anything with the group, like test if it ends with 0s. Am I on the right track? Commented Mar 8, 2022 at 19:14

1 Answer 1

3

You might shorten the pattern to match either a dot with only zeroes, or use a non greedy match for the digits with a capture group and match optional trailing zeroes.

If you want to match digits and comma's the first \d+ can also be [\d,]+ as you already have in your pattern.

If there should be at least a single digit after the dot, then the quantifier can be a plus .\d+?

^(\d+)(?:\.0+|(\.\d*?)0+)$

See a regex 101 demo.

[
  "1.7500",
  "1.1010",
  "1.0000",
  "10"
].forEach(s =>
  console.log(s.replace(/^(\d+)(?:\.0+|(\.\d*?)0+)$/, "$1$2"))
);

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

1 Comment

Thanks, that simplifies the solution I found...

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.