Reputation: 1257
Over here I was asked to form a new question with one of my comments so here I am. I was wondering if it was possible to replace a phrase within certain words only. Eg: Replacing the BAB
in CBABAC
but not the BAB
in DABABCC
Thanks!
Upvotes: 1
Views: 76
Reputation: 34556
You don't say what the basis is for the logic of the replacement, so this is a generalised answer.
As some have mentioned, you could use a lookahead, but one of the major annoyances of JavaScript is that it doesn't natively support lookbehinds, so you have only half a solution there.
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.
Let's say I want to replace all instances of foo
with bar
, where it is preceded and proceded by a number.
var str = 'foo 1foo1 foo2';
console.log(str.replace(/(\d)foo(?=\d)/g, function($0, $1) {
return $1+'bar';
})); //foo 1bar1 foo1
So I use a lookahead for the easy part, and a callback to compensate for the lack of lookbehind.
There are implementations of lookbehind in JS, including one I wrote, 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(?=\d)/g, 'bar', '(?<=\\d)'));
Upvotes: 0
Reputation: 11182
Use lookahead:
BAB(?=AC)
Explanation
"BAB" + // Match the characters “BAB” literally
"(?=" + // Assert that the regex below can be matched, starting at this position (positive lookahead)
"AC" + // Match the characters “AC” literally
")"
or
BAB(?!CC)
Explanation
"BAB" + // Match the characters “BAB” literally
"(?!" + // Assert that it is impossible to match the regex below starting at this position (negative lookahead)
"CC" + // Match the characters “CC” literally
")"
Upvotes: 2