Posted By

kouphax on 11/11/08


Tagged

escape regex javascript


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

robe
wizard04


Escape Regular Expression Characters in String


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/280793/case-insensitive-string-replacement-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.