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, "\\$&");
}
Sign up to request clarification or add additional context in comments.

3 Comments

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
Used here as well: github.com/jquery/jquery-ui/blob/master/ui/… (search for escapeRegex)
How to escape / symbol?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.