views:

37

answers:

2

I just want to create a regular expression out of any possible string.

var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);

Is there a built in method for that? If not, what do people use? Ruby has RegExp.escape. I don't feel like I'd need to write my own, there's gotta be something standard out there. Thanks!

A: 

Such function ready to be used:

http://snipplr.com/view/9649/escape-regular-expression-characters-in-string/

Leniel Macaferi
it's crazy this isn't in the standard library! thanks a lot though. using it :)
viatropos
+5  A: 

The function linked above is insufficient. It fails to escape ^ or $ (start and end of string), or -, which in a character group is used for ranges.

Try:

RegExp.escape= function(s) {
    return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
};

And yes, it is a disappointing failing that this is not part of standard JavaScript.

bobince