ChiMo
ChiMo

Reputation: 601

Javascript Regex - Replace all occurences of matching string EXCEPT any string between brackets

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

Answers (2)

bobble bubble
bobble bubble

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

Tushar
Tushar

Reputation: 87203

Use Negative lookahead

Regex Demo

(?!\{)replace(?!\})
  1. (?!\{): Negative Lookahead - Assert that it is impossible to match { literal
  2. replace: Matches replace string literally
  3. (?!\}): Negative Lookahead - Assert that it is impossible to match } literal

Javascript Demo

var str = "replace {replace} test replacesreplace";
var replacedStr = str.replace(/(?!\{)replace(?!\})/g, "%");

document.write(replacedStr);

Upvotes: 1

Related Questions