An404 An404 - 4 months ago 9
Javascript Question

javascript regex to select quoted string but not escape quotes

Original string:

some text "some \"string\"right here "


Want to get:

"some \"string\"right here"


I am using the following regex:

/\"(.*?)\"/g

Answer

It is not possible to match the string you need with lazy dot matching pattern since it will stop before the first ".

You need to use

/"([^"\\]*(?:\\.[^"\\]*)*)"/g

See the regex demo

  • " - match a quote
  • ([^"\\]*(?:\\.[^"\\]*)*) - 0 or more sequences of
    • [^"\\]* - 0+ non-\ and non"s
    • (?:\\.[^"\\]*)* - zero or more sequences of
      • \\. - any escaped symbol
      • [^"\\]* - 0+ non-\ and non"s
  • " - trailing quote

JS demo:

var re = /"([^"\\]*(?:\\.[^"\\]*)*)"/g; 
var str = `some text "some \\"string\\"right here " some text "another \\"string\\"right here "`;
var res = [];
while ((m = re.exec(str)) !== null) {
   res.push(m[1]);
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>"; // Just for demo
console.log(res); // or another result demo