function addSlashes(str) { str = str.replace(/\[/g, '\\['); str = str.replace(/\\/g, '\\\\'); str = str.replace(/\^/g, '\\^'); str = str.replace(/\$/g, '\\$'); str = str.replace(/\|/g, '\\|'); str = str.replace(/\?/g, '\\?'); str = str.replace(/\*/g, '\\*'); str = str.replace(/\+/g, '\\+'); str = str.replace(/\./g, '\\.'); str = str.replace(/\(/g, '\\('); str = str.replace(/\)/g, '\\)'); return str; } 
  • @AlexeyTen Make an answer - put a daw. - user208916
  • @AlexeyTen Yes, just make a link with the answer and that's it. The link may also be the answer. Why not? It is not necessary to generate creative. - user208916
  • Everything is already decided in the English version. stackoverflow.com/q/3561493/1016033 - Alexey Ten
  • one
    @Khipster I do not interpret the rules, I am trying to convey to you their essence. The answer should be self-sufficient, so that future visitors can use it directly. The link can only be a supplement to the answer. It's simple. The code RegExp.escape right in the answer + link is the answer. Just a link to "here's a great solution!" - not the answer. - PashaPash

3 answers 3

Everything has already been decided in the English version: https://stackoverflow.com/a/3561711/1016033

 RegExp.escape = function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; 

    You can collect everything in one expression and specify the group number

     function addSlashes(str) { return str.replace(/(\[|\\|\^|\$|\||\?|\*|\+|\.|\(|\))/g, '\\$1'); } console.log(addSlashes('.*')); 

       function addSlashes(str) { // Сливаем все регулярки в одну // Сохраняем спец. символ в группу и экранируем его return str.replace(/(\[|\\|\^|\$|\||\?|\*|\+|\.|\(|\))/g, "\\$1"); } console.info(addSlashes('some[\\T^Q$I|K?H*N+BP()]'));