1

Is there a way to replace a string which is not in id="<any_characters>"?

I only found this How to replace a string which is not in quotes which doesn't replace a string in quotes.

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

However, I want that the string can be replaced in quotes like "replace" but id="don't replace" shouldn't be replaced.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
GreenTigerEye
  • 5,917
  • 9
  • 22
  • 33

1 Answers1

1

The expression can be:

id="[^"]+"|(replace)
# id = "..." or replace


Additionally, you'll need some programming logic here:

var subject = '"replace" but id="don\'t replace" some lorem ipsum';
var regex = /id="[^"]+"|(replace)/g;

replaced = subject.replace(regex, function(m, group1) {
    if (typeof(group1) == 'undefined') return m;
    else return "some other string here";
});
console.log(replaced);

The idea here is to match id="..." but not to capture it. The only occurrences of replace will be captured outside of id="...". In languages with PCRE support, this can be achieved via (*SKIP)(*FAIL) directly in the expression but JavaScript lacks support thereof.
Jan
  • 42,290
  • 8
  • 54
  • 79
  • Hmm, i wanted to use the pattern with the programming language Dart. Unfortunately, there is no method which supports functions like you used with replace(regex, function(m, group1)) . Is there any other way without the use of functions as a second argument or only to use regex patterns? – GreenTigerEye Dec 13 '17 at 20:54
  • 1
    Nice answer. If you want to capture escaped double quotes in strings you can use `id="(?:[^"\\]|\\.)*"|(replace)` (as per [this answer](https://stackoverflow.com/questions/249791/regex-for-quoted-string-with-escaping-quotes)) +1 – ctwheels Dec 13 '17 at 20:56
  • @GreenTigerEye: I am by now means an expert in `dart` - maybe they support `(*SKIP)(*FAIL)` ? https://api.dartlang.org/stable/1.24.3/dart-core/RegExp-class.html But honestly, I doubt it. – Jan Dec 13 '17 at 21:01