Posted By

kouphax on 11/11/08


escape regex javascript

Versions (?)

Who likes this?

2 people have marked this snippet as a favorite


Escape Regular Expression Characters in String

 / Published in: JavaScript


Escape all special regex characters (.*+?|()[]{}) from a string. Useful when dynamically building a Regular Expression object based on input text that could hold regex characters.

  1. RegExp.escape = function(str)
  2. {
  3. var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
  4. return str.replace(specials, "\\$&");
  5. }

Report this snippet  

You need to login to post a comment.