Search code examples
javascriptregexescaping

List of all characters that should be escaped before put in to RegEx?


Could someone please give a complete list of special characters that should be escaped?

I fear I don't know some of them.


Solution

  • PHP's preg_quote function takes arbitrary strings and "puts a backslash in front of every character that is part of the regular expression syntax" and it escapes these characters:

    . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
    

    Here is a simplified version of the JavaScript re-implementation of preg_quote from Locutus:

    function escapeRegexChars(str) {
      return str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g'), '\\$&')
    }