I just want to create a regular expression with 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? If not, what do people use? Ruby has RegExp.escape
. I feel like I don't need to write my own, there must be some standard.
For anyone using Lodash, As of v3.0.0 the _.escapeRegExp function is built-in:
And, if you don't want to need the full Lodash library, you may want That's it!
The functionality linked in the other answer is insufficient. It cannot escape
^
or$
(beginning and end of string) or-
, which are used in character groups for ranges.Use this function:
Although it may seem unnecessary at first glance, escaping
-
(as well as^
) makes this function also suitable for escaping characters to be inserted into character classes as regular expressions the subject.Escapes
/
Makes this function suitable for escaping characters to be used in JavaScript regular expression literals for later evaluation.Since there is no harm in escaping any of them, it makes sense to escape to cover a wider range of use cases.
Yes, disappointingly, this is not part of standard JavaScript.