Skip to main content
hank-builds.com

Quoted String regex

Matches single or double quoted strings with escape support.

/(["'])(?:(?!\1|\\).|\\.)*\1/g

What it matches

A single or double quoted string where the closing quote must be the same character as the opening one: that is the \1 backreference. The body allows any character that is not the delimiter or a backslash, plus any backslash escape, so an escaped quote inside the string does not end it early.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

Group ["'] (?!...) \1 \\ . \\ . \1

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
["']Match one of: Literal """, Literal "'"
.Any character
\\Literal "\"
.Any character
\1Backreference to group #1

Test cases

Matches

  • "hello world"
  • 'single quoted'
  • ""

Does not match

  • no quotes here
  • "unterminated

Caveats

It understands backslash escaping only. Doubled-quote escaping, as used by SQL and CSV, ends the match at the first of the pair. Template literals and triple-quoted strings are outside its scope, and an unterminated quote simply fails to match rather than reporting an error.

More text processing patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.