简体   繁体   中英

lookbehind in javascript?

I wanted to use regex to match and replace anything between my file name and closing parentheses.

I wrote a regex:

/(?<=imagecheck.php)[^)]*/

That works in php, but not in Javascript.

...How would I do in JS?

example:

 input string example 1: url(127.0.0.1/imagecheck.php)
 input string example 2: url(127.0.0.1/imagecheck.php?boost=9881732213826123918238)
 outcome string example: url(127.0.0.1/imagecheck.php?reload=oh_yes_plx&boost=123810982346023984723948723023423)

Look-behind is not supported in Javascript. You can use capturing group to capture the text after "imagecheck.php" instead:

.match(/imagecheck.php([^)]*)/)

The result will be in index 1 of the returned array (if there is a match).

This is an example of removing whatever after "imagecheck.php"

.replace(/(imagecheck.php)[^)]*/, "$1")

Without look-behind in javascript, you can replace everything between your filename and the closing paren like this:

str = str.replace(/imagecheck.php\([^)]*\)/, "imagecheck.php(whatever)");

or, you can use capture groups and numbered references to avoid repeating the initial pattern:

str = str.replace(/(imagecheck.php)\([^)]*\)/, "$1(whatever)");

XRegExp doesn't support lookbehind directly. For that, you'd need to use the addon script previously linked to by @arxanas: http://blog.stevenlevithan.com/archives/javascript-regex-lookbehind . Also, XRegExp doesn't use forward-slash delimiters within its pattern strings.

Though Javascript doesn't natively support lookbehind in regular expressions, we could pull in XRegExp , a more powerful Javascript regex engine.

var pattern = XRegExp('/(?<=imagecheck.php)[^)]*/', 'g'); // g is the global flag
XRegExp.replace(input, pattern, replacement);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM