1

im struggling with the following scenario, i have a multiline string which has the word test multiple times inside, the string is:

Hello my name is "test" im a test
test is testing

i need to replace all the test -strings which are not in quotes every of the found ones should be followed by at least 1 whitespace OR a linebreak not by anything else, so the above string would transform into:

Hello my name is "test" im a HELLOWORLD
HELLOWORLD is testing

also the test -string could be prepended by whitespaces, but not also without.

What i already found out is a method to only replace a string which is not inside of quotes:

str.replace(/(test)(?=(?:[^"]|"[^"]*")*$)/, 'HELLOWORLD')

could sombebody give me a hand with finding the other rules?

beist87
  • 43
  • 4
  • i would also like to include single-quotes, so neither "test" nor 'test' would get replaced – beist87 Mar 20 '15 at 16:06
  • See https://stackoverflow.com/questions/15741243/replace-string-everywhere-except-if-its-within-quotes/69428257#69428257 – user1432181 Oct 03 '21 at 19:34

2 Answers2

3
(\btest\b)(?=(?:[^"]|"[^"]*")*$)

Try this.See demo.

https://regex101.com/r/pT4tM5/28

vks
  • 67,027
  • 10
  • 91
  • 124
1

You can use:

var str = 'Hello my \'test\' name is "test" im a test\ntest is testing';
var repl = str.replace(/("[^"]*"|'[^']*')|\btest\b/g, function($0, $1) { 
           return ($1 == undefined) ? "HELLOWORLD" : $1; });

Output:

Hello my 'test' name is "test" im a HELLOWORLD
HELLOWORLD is testing
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • does not work as expected because 'another' would get replaced with HELLOWORLD – beist87 Mar 20 '15 at 16:38
  • That's not correct, have you tried given code in answer. As you can see `'test'` remains unchanged above. – anubhava Mar 20 '15 at 16:46
  • 1
    im sorry, you are right, it works. I just copied the regex pattern and replaced it in my code ad there it didnt work. – beist87 Mar 20 '15 at 16:56