I'm trying to use Regex to match a zero followed by a dot and exactly 6 digits. Such as --> 0.274538
The 6 digits can be any number 0-9. Also, any characters (including blank spaces) may exist before or after the match.
I would like to trim the tailing 4 digits off of the match, so that the result is a zero followed by 2 decimal places (ie 0.27).
I'm using this regex inside a Javascript string replace function. I'm including the "g" modifier, as there will be several matches within the string.
I'm not very good with regex, but I think the following code is pretty close to what I need...
var replaced = string.replace(/[0]\.[0-9]{6}$/g, X);
Only thing is... I'm not sure what to use for the 'replace' value here (X). If there was only one match expected, then I could just use "slice" on the replaced string. But since I am expecting several regex matches in the string, what should I use for the "X" value? Or is there a better way to go about this?
You can use capturing group:
var s = '0.274538'
var r = s.replace(/\b(0\.\d{2})\d{4}\b/g, '$1');
//=> 0.27
\b
is for word boundary.(..)
is captured group #1 to grab 0
followed by a DOT and 2 decimal point.$1
is back-reference of captured group#1This is another way of doing it, with a function
as a the replace 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With