Not sure if you want to replace "Level 2
and Level 2"
or not, so I offer solutions for both scenarios:
1) If you want to replace only those with not even a single "
:
(?<!")(Level\s\d+)(?!")
see https://regex101.com/r/Nc7b5h/1
This uses a negative look-behind and a negative look-ahead
2) However, if you also want to replace those with only one "
, try this:
(?!"Level\s\d+")(?<!")"?Level\s\d+"?
https://regex101.com/r/qL5Li5/1/
Set your match group based on whether you want to replace the single "
or not:
var s='This "Level 2" is "Level 2 a Level 2" test Level 2 :)'
s.replace(/(?!"Level\s\d+")(?<!")"?(Level\s\d+)"?/g, '"$1"');
//> 'This "Level 2" is "Level 2" a "Level 2" test "Level 2" :)'
or
var s='This "Level 2" is "Level 2 a Level 2" test Level 2 :)'
s.replace(/(?!"Level\s\d+")(?<!")("?Level\s\d+"?)/g, '"$1"');
//> 'This "Level 2" is ""Level 2" a "Level 2"" test "Level 2" :)'
The trick here was to first perform a negative look-ahead for the forbidden case of a match with two "
, before doing anything else.
General Notes
If you don't want to use a look-behind expression ((?<!")
) as older browsers (pre-ES2018) won't support that, just use (^|[^"])
instead, as other suggested. Just don't forget to restore its contents in the replacement :)
e.g. s.replace(/(?!"Level\s\d+")(^|[^"])"?(Level\s\d+)"?/g, '$1"$2"');