Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Is there a regular expression library that fully supports lookarounds?

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).

like image 375
try-catch-finally Avatar asked Nov 14 '22 01:11

try-catch-finally


1 Answers

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)'));
like image 97
Mitya Avatar answered Dec 21 '22 18:12

Mitya