Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple jQuery / javascript method to escape special characters in string for regexp

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?)

like image 482
John Hunt Avatar asked Mar 15 '11 00:03

John Hunt


1 Answers

Found a function here:

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
like image 116
John Hunt Avatar answered Nov 03 '22 15:11

John Hunt