10

I'm performing a regular expression using the match() method on a string that comes from the user and could contain anything, including $^'s etc.. so I need to escape those characters before this happens.

Is there a common function in jQuery to do this, a well known javascript function or am I going to have to do it manually (with the chance I might miss something?)

0

1 Answer 1

13

Found a function here:

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
2
  • 1
    as far as I can see, it's the same replacement as in jQuery.ui.autocomplete.escapeRegex, however this function is not official and can therefor be removed at any time without further notice
    – StrubT
    Sep 25, 2012 at 20:49
  • Used here as well: github.com/jquery/jquery-ui/blob/master/ui/… (search for escapeRegex)
    – Salman A
    Dec 16, 2012 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.