JavaScript regex: Positive lookbehind alternative (for Safari and other browsers that do not support lookbehinds)

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]);
}

Or, to get all matches:

const s = "some string.005 some string.006";
const rx = /\.\d\d(\d)/g;
let result = [], m;
while (m = rx.exec(s)) {
  result.push(m[1]);
}
console.log( result );

An example with matchAll:

const result = Array.from(s.matchAll(rx), x=>x[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);

Leave a Comment