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!
There is an ES7 proposal for RegExp.escape at https://github.com/benjamingr/RexExp.escape/, with a polyfill available at https://github.com/ljharb/regexp.escape.
The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).
If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (
.
,?
,+
,*
,^
,$
,|
,\
) or start something ((
,[
,{
) is all you need:And yes, it's disappointing that JavaScript doesn't have a function like this built-in.
In jQueryUI's autocomplete widget (version 1.9.1) they use a slightly different regex (Line 6753), here's the regular expression combined with @bobince approach.
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.Use this function:
While it may seem unnecessary at first glance, escaping
-
(as well as^
) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.Escaping
/
makes the function suitable for escaping characters to be used in a JS regex literal for later eval.As there is no downside to escaping either of them it makes sense to escape to cover wider use cases.
And yes, it is a disappointing failing that this is not part of standard JavaScript.
For anyone using lodash, since v3.0.0 a _.escapeRegExp function is built-in:
And, in the event that you don't want to require the full lodash library, you may require just that function!