I asked this question to chatGpt, he gave me this regex and example:
let str = '"This is a "test" string with "quotes" in the middle."';
let result = str.replace(/(?<=^|[^"])(")(?=S.*")/g, 'replacement');
console.log(result);
But I still get the first double quotes in the begining of the string replaced
//replacementThis is a replacementtest" string with replacementquotes" in the middle."
I need only the doubles quotes in the middle to be replaced, not in the beginning or the end.
2
Answers
Just assert that before the quote we’re not at the start of the string, and that after the quote we’re not at the end of it:
That is because your pattern starts with an alternation
(?<=^|[^"])
asserting either the start of the string or a character other than"
directly to the left (where the negated charcter class[^"]
could also match a newline)If you want to use positive lookaround assertions, you can assert that there should be a character to the left and to the right, where the dot can also match a space:
See a regex demo
If there should be a non whitespace character other than
"
to the left and to the right:See a regex demo.