Reputation: 601
I need to replace a string that has has instances inside another but ignore replacing any string if it is inside curly braces.
I have tried the following:
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "%")
// % % test %%
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "$1"+"%")
// replace% % test replaces%replace%
But I need the replace to look like this: "% {replace} test %%"
Can anyone suggest how to do this inside Javascript?
Upvotes: 1
Views: 320
Reputation: 18490
You can use a function with String.replace()
. If capture is found, braced stuff is returned, else %
.
var str = "replace {replace} test replacesreplace";
str = str.replace(/({[^}]*})|replaces?/g, function($0, $1) {
return typeof $1 != 'undefined' ? $1 : "%";
});
document.write(str);
Upvotes: 3
Reputation: 87203
Use Negative lookahead
(?!\{)replace(?!\})
(?!\{)
: Negative Lookahead - Assert that it is impossible to match {
literalreplace
: Matches replace
string literally(?!\})
: Negative Lookahead - Assert that it is impossible to match }
literalJavascript Demo
var str = "replace {replace} test replacesreplace";
var replacedStr = str.replace(/(?!\{)replace(?!\})/g, "%");
document.write(replacedStr);
Upvotes: 1