Match zero to six decimal places

I am trying to use Regex to match zero, followed by a period and exactly 6 digits. Such as โ†’ 0.274538

6 digits can be any number 0-9. In addition, any symbols (including spaces) may exist before or after the match.

I would like to trim the tail 4 digits from the match, so the result is zero, and then 2 decimal places (i.e. 0.27).

I use this regular expression inside the Javascript string replacement function. I turn on the "g" modifier, as there will be several matches in the line.

I am not very good at regular expression, but I think the following code is pretty close to what I need ...

var replaced = string.replace(/[0]\.[0-9]{6}$/g, X);

Only ... I'm not sure what to use for the "replace" value here (X). If only one match was expected, then I could just use a โ€œsliceโ€ on the replaced string. But since I expect some regular expressions in a string, what should I use for the value of "X"? Or is there a better way to do this?

+4
source share
2 answers

You can use capture group:

var s = '0.274538'
var r = s.replace(/\b(0\.\d{2})\d{4}\b/g, '$1');
//=> 0.27
  • \b for the border of the word.
  • (..)capture group # 1 is captured 0, followed by a DOT and 2 decimal points.
  • $1 - backlink of captured group # 1
+6
source

This is another way to do this: functionas a replacement parameter:

var regex = /0\.\d{6}/g;
var num = '0.543456';

var trimmed = num.replace(regex, function(match){
  return match.substr(0, match.length - 4);
  });

console.log(trimmed);
Run codeHide result
+1

Source: https://habr.com/ru/post/1612961/


All Articles