I need to use lookbehind of regex in JavaScript, so found Simulating lookbehind in JavaScript (take 2). Also, I found the author Steven Levithan is the one who developed XRegExp.
I git cloned XRegExp 3.0.0-pre, and tested
some lookbehind logic http://regex101.com/r/xD0xZ5 using XRegExp
var XRegExp = require('xregexp');
console.log(XRegExp.replace('foobar', '(?<=foo)bar', 'test'));
It seems not working;
$ node test
foobar
What do I miss? Thanks.
EDIT: My goal is something like
(?<=foo)[\s\S]+(?=bar)
(EDIT2 the link was wrong and modifed)
Answer:
var str = "fooanythingbar";
console.log(str);
console.log(str.replace(/(foo)(?:[\s\S]+(?=bar))/g, '$1test'));
//footestbar
Credit goes to @Trevor Senior Thanks!
It is possible to use non-capturing groups for this, e.g.
$ node
> 'foobar'.replace(/(foo)(?:bar)/g, '$1test')
'footest'
In the second parameter of String.replace, the special notation of $1
references the first capturing group, which is (foo)
in this case. By using $1test
, one can think of $1
as a placeholder for the first matching group. When expanded, this becomes 'footest'
.
For more in depth details on the regular expression, view what it matches here.