JavaScript regex: Positive lookbehind alternative

I am looking for an alternative for this:

(?<=\.\d\d)\d

(Match third digit after a period.)

I'm aware I can solve it by using other methods, but I have to use a regular expression and more importantly I have to use replace on the string, without adding a callback.

Answers:

Answer

Turn the lookbehind in a consuming pattern and use a capturing group:

And use it as shown below:

var s = "some string.005";
var rx = /\.\d\d(\d)/;
var m = s.match(/\.\d\d(\d)/);
if (m) {
  console.log(m[1]);
}

EDIT:

To remove the 3 from the str.123 using your current specifications, use the same capturing approach: capture what you need and restore the captured text in the result using the $n backreference(s) in the replacement pattern, and just match what you need to remove.

var s = "str.123";
var rx = /(\.\d\d)\d/; 
var res = s.replace(rx, "$1");
console.log(res);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.