Reputation: 12708
I want to replace {r-group1}
with "REPLACED" but leave the ,
where it is.
So, the string
var string = "{r-group1, }foo bar"
should output: "REPLACED, foo bar"
Using a negative lookahead, I tried adding a preceding (?![,])
group to leave the comma alone:
var replaced = string.replace(^(?:(?![,]){r-group1\})+$, 'REPLACED');
But it returns the same string. There are no matches to replace.
The same goes for a preceding comma:
var string = "foo bar{r-, group1}"
This should output: "foo bar, REPLACED"
Upvotes: 0
Views: 1258
Reputation: 163207
You could do the replacement without a lookahead. You could match the curly braces and the content that comes before and after it except a comma using a negated character class [^,}]+
and capture the comma with optional whitespace chars in a capturing group.
In the replacement use the capturing groups $1REPLACED$2
Credits to @Nick for the updated pattern.
{r-(,?\s*)[^,}]+(,?\s*)}
const regex = /{r-(,?\s*)[^,}]+(,?\s*)}/g;
const str = `{r-group1, }foo bar`;
const subst = `$1REPLACED$2`;
const result = str.replace(regex, subst);
console.log(result);
Upvotes: 2