back to the lesson

Find quoted strings

Create a regexp to find strings in double quotes "...".

The strings should support escaping, the same way as JavaScript strings do. For instance, quotes can be inserted as \" a newline as \n, and the backslash itself as \\.

let str = "Just like \"here\".";

Please note, in particular, that an escaped quote \" does not end a string.

So we should search from one quote to the other ignoring escaped quotes on the way.

That’s the essential part of the task, otherwise it would be trivial.

Examples of strings to match:

.. "test me" ..
.. "Say \"Hello\"!" ... (escaped quotes inside)
.. "\\" ..  (double backslash inside)
.. "\\ \"" ..  (double backslash and an escaped quote inside)

In JavaScript we need to double the backslashes to pass them right into the string, like this:

let str = ' .. "test me" .. "Say \\"Hello\\"!" .. "\\\\ \\"" .. ';

// the in-memory string
alert(str); //  .. "test me" .. "Say \"Hello\"!" .. "\\ \"" ..

The solution: /"(\\.|[^"\\])*"/g.

Step by step:

  • First we look for an opening quote "
  • Then if we have a backslash \\ (we have to double it in the pattern because it is a special character), then any character is fine after it (a dot).
  • Otherwise we take any character except a quote (that would mean the end of the string) and a backslash (to prevent lonely backslashes, the backslash is only used with some other symbol after it): [^"\\]
  • …And so on till the closing quote.

In action:

let regexp = /"(\\.|[^"\\])*"/g;
let str = ' .. "test me" .. "Say \\"Hello\\"!" .. "\\\\ \\"" .. ';

alert( str.match(regexp) ); // "test me","Say \"Hello\"!","\\ \""