skip to Main Content

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


  1. 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:

    let str = '"This is a "test" string with "quotes" in the middle."';
    let result = str.replace(/(?!^)"(?!$)/g, '#');
    console.log(result);
    Login or Signup to reply.
  2. But I still get the first double quotes in the begining of the string
    replaced

    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

    let str = '"This is a "test" string with "quotes" in the middle."';
    let result = str.replace(/(?<=.)"(?=.)/g, '[replacement]');
    console.log(result);

    If there should be a non whitespace character other than " to the left and to the right:

    (?<=[^s"][^"n]*)"(?=[^"n]*[^s"])
    

    See a regex demo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search