Home > Software engineering >  Javascript Regular Expressions - Replace non-numeric characters
Javascript Regular Expressions - Replace non-numeric characters

Time:12-20

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, '')

CodePudding user response:

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.

CodePudding user response:

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.

  • Related