JavaScript: Does the RegExp.escape function exist?
P粉381463780
P粉381463780 2023-11-16 17:41:27
0
2
782

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.

P粉381463780
P粉381463780

reply all(2)
P粉662089521

For anyone using Lodash, As of v3.0.0 the _.escapeRegExp function is built-in:

_.escapeRegExp('[lodash](https://lodash.com/)');
// → '\[lodash\]\(https:\/\/lodash\.com\/\)'

And, if you don't want to need the full Lodash library, you may want That's it!

P粉734486718

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:

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

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template