0

I have this line:

val = val.replace(/[^0-9\.]/g, '')

and it replaces anything that is not a number, but I need a regular expression that limits val to be 2 numbers, period and then 2 numbers, like this:

- 11.33
- 12.34
- 54.65

I've already tried something like this but it didn't work:

val = val.replace(/^[^0-9\.]{1,2}/g, '')
2
  • What would happen to a number like 123.456? Commented Dec 17, 2022 at 0:26
  • Why not just parse and then print with precision of 2 decimal places, after match, using replace function? Commented Dec 17, 2022 at 0:28

2 Answers 2

1

Normally with replace you scan the entire string and keep the middle part. So start with beginning (^), scan some stuff you don't care about (.), then scan your number ([0-9]{1,2}(?:.[0-9]{0-2})?), then scan the rest which you don't care about (.), then you're at the end ($).

Then you replace with the middle capture group.

val.replace(/^(.*)([0-9]{1,2}(?:\.[0-9]{0-2})?)(.*)$/gm,'\2');

Use the m flag to process line by line.

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

1 Comment

The idea looks good, but there are issues with your code: 1.) If you use .* in first group it will consume anything up to the last digit, rather use lazy .*? 2.) The {0-2} quantifier should be {0,2} 3.) The replacement is rather $2 than \2 (working demo).
0

Sometimes it is easier to use multiple regexes instead of one. Here is a solution that uses a first regex to strip the string from anything but number digits, then a second regex that reduces the number string to the proper length:

const regex1 = /[^\d\.]/g;
const regex2 = /^.*(\d\d\.\d\d).*$/;
[
  'aaa11.33zzz',
  'aaa123.456zzz',
  '-54.65',
  '12xtra.34'
].forEach(str => {
  let result = str.replace(regex1, '').replace(regex2, '$1');
  console.log(str, '==>', result);
});

Output:

aaa11.33zzz ==> 11.33
aaa123.456zzz ==> 23.45
-54.65 ==> 54.65
12xtra.34 ==> 12.34

Explanation of regex1:

  • [^\d\.] -- anything not 0-9 and .
  • g -- flag to replace pattern multiple times

Explanation of regex2:

  • ^ -- anchor at start of string
  • .* -- greedy scan
  • (\d\d\.\d\d) -- expect 2 digits, a dot, and 2 digits
  • .* -- greedy scan
  • $ -- anchor at end of string

You did not specify what should happen if the input string has less than the 2digits, dot, 2 digits pattern. So this solution does not address that case.

Comments

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.