I want to replace only the characters outside "" with a regular expression

Viewed 66

I want to get the result with regular expression

var text = "\"1test2test3\"test123test45test\"67test89\"";

text.replaceAll(/\"(.*)\"/g, "boom");

boom

but I want

var text = "\"1test2test3\"test123test45test\"67test89\"";

text.replaceAll(????, "boom");

"\"1test2test3\"boom123boom45boom\"67test89\"";
1 Answers

You can use

.replace(/("[^"]*")|test/g, (x,y) => y ? y : "boom")

Details:

  • ("[^"]*") - Capturing group 1: a ", then any zero or more chars other than a " and then a "
  • | - or
  • test - a test string.

The (x,y) => y ? y : "boom" replacement means that whenever Group 1 (y) matches, this group value is returned, else (if test is found in all other contexts), boom is returned.

See the JavaScript demo:

var text = "\"1test2test3\"test123test45test\"67test89\"";
console.log(text.replace(/("[^"]*")|test/g, (x,y) => y ? y : "boom"));

Related