As JavaScript’s built-in regular expression library does not support lookbehind, I wondered if there’s a library that implements a regular expression engine purely in JavaScript.
In my case, the performance does not matter (as long as searching for simple expressions in short strings does not take seconds or longer).
A common workaround for the lack of look-behind is to match (rather than anchor to) what comes before the bit you're interested in, then reinsert it in the callback.
To replace all instances of foo
with bar
, where it is preceded by a number.
var str = 'foo 1foo foo2';
console.log(str.replace(/(\d)foo/g, function($0, $1) {
return $1+'bar';
})); //foo 1bar foo1
There are implementations of lookbehind in JS, including one I wrote (docs; code), where a positive or negative lookbehind is passed as an extra parameter. Using that, this would get the same result as the above:
console.log(str.replace2(/foo/g, 'bar', '(?<=\\d)'));
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