JavaScript doesn't support lookbehind. This is a shame, as we could have done:
// doesn't work in JavaScript:
/((apple|banana|cherry|orange)\b\s?)+(?<!\s)/gi
What we can do, however, is to move the white-space to the beginning, and add a negative lookahead (so the catch must not start with a white-space):
/(?!\s)(\s?\b(apple|banana|cherry|orange)\b)+/gi
A slight difference from your code is that I also added \b
to the beginning of the pattern, so it wouldn't catch apple
from Snapple
.
Вы можете поместить функцию в параметр замены как
function (x) {return "" + x.replace (/ \ s + $ /, "") + "< em> ";}
вместо $ &
, и вы можете поместить пробел в эту функцию.
"Apple Banana apple cherry, Cherry orange and Oranges Apple, Banana".replace(
/((?:apple|banana|cherry|orange)\b\s?)+/gi,
function(x){
return "<em>"+x.replace(/\s+$/,"")+"<em>";
})
<em>Apple Banana apple cherry<em>, <em>Cherry orange<em>and Oranges <em>Apple<em>, <em>Banana<em>