Question

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)

http://regex101.com/r/sV5gD5

(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!

Was it helpful?

Solution 2

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.

OTHER TIPS

I want to give an update on the state of affairs.

Lookahead assertions have been part of JavaScript’s regular expression syntax from the start. Their counterpart, lookbehind assertions, are finally being introduced ... *in Google Chrome 62
Source: https://developers.google.com/web/updates/2017/07/upcoming-regexp-features

If you run this in with Chrome 62+, v8 6.2.414 you will get the expected result: footest
- independent of XRegex!

 
var x = XRegExp('(?<=foo)bar', 'g');
console.log(XRegExp.replace('foobar', x, 'test'));

console.log("foobar".replace( new RegExp('(?<=foo)bar',"g"),"test"));
<script src="https://unpkg.com/xregexp/xregexp-all.js"></script>

However, no other browser supports lookbehind assertions yet - not even node.js, which is based on v8 (tested with node v9.7.1/v8 6.2.414.46, but I expect it will be added in upcoming node releases.)

Hopefully, other vendors will follow soon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top