Javascript regex to escape quotes (but not escape already escaped quotes)

后端 未结 4 1300
情歌与酒
情歌与酒 2021-01-13 19:22

I am looking for a JavaScript regex which will escape single quotes but it should not escape single quotes which are already escaped.

4条回答
  •  醉话见心
    2021-01-13 19:59

    Ideally, you want every match to start exactly where the previous match ended. Otherwise it's too easy to get out of sync with the escape sequences. @outis's regex comes close, but it fails to escape the second single-quote in '\\'. After the first match, it has to match at least one non-backslash and one single-quote, which it can't do. If there are any more characters, it skips ahead and starts matching after the second single-quote.

    Try this one instead:

    result = subject.replace(/([^'\\]*(?:\\.[^'\\]*)*)'/g, "$1\\'");
    

    This is an example of Friedl's "unrolled loop" pattern:

    normal * (special normal *) *

    [^'\\]* is the "normal *" part; it gobbles up any number of characters other than single-quotes or backslashes. If the next character is a backslash, \\. ("special") consumes that and the next character (backslash, single-quote, or whatever) and [^'\\]* takes over again. Repeat as needed.

    The key point is that the regex never skips ahead and it never backtracks. If it sees a backslash, it always consumes that and the next character, so it never gets out of sync.

提交回复
热议问题