Escape Regular Expression Characters in String

/ Published in: JavaScript
Save to your folder(s)

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.

Copy this code and paste it in your HTML
  1. RegExp.escape = function(str)
  2. {
  3. var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
  4. return str.replace(specials, "\\$&");
  5. }


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.