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

Solution 1:

Take a look at PHP.JS's implementation of PHP's preg_quote function, that should do what you need:

http://phpjs.org/functions/preg_quote:491

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Solution 2:

According to this site, the list of characters to escape is

[, the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening round bracket ( and the closing round bracket ).

In addition to that, you need to escape characters that are interpreted by the Javascript interpreter as end of the string, that is either ' or ".

Solution 3:

Based off of Tatu Ulmanen's answer, my solution in C# took this form:

private static List<string> RegexSpecialCharacters = new List<string>
{
    "\\",
    ".",
    "+",
    "*",
    "?",
    "[",
    "^",
    "]",
    "$",
    "(",
    ")",
    "{",
    "}",
    "=",
    "!",
    "<",
    ">",
    "|",
    ":",
    "-"
};


foreach (var rgxSpecialChar in RegexSpecialCharacters)
                rgxPattern = input.Replace(rgxSpecialChar, "\\" + rgxSpecialChar);

Note that I have switched the positions of '\' and '.', failure to process the slashes first will lead to doubling up of the '\'s

Edit

Here is a javascript translation

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

regexSpecialCharacters.forEach(rgxSpecChar => 
    input = input.replace(new RegExp("\\" + rgxSpecChar,"gm"), "\\" + 
rgxSpecChar))