Is there a RegExp.escape function in Javascript?

2018-12-30 23:16发布

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!

12条回答
倾城一夜雪
2楼-- · 2018-12-30 23:32

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.

查看更多
妖精总统
3楼-- · 2018-12-30 23:34

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:

String.prototype.regexEscape = function regexEscape() {
  return this.replace(/[.?+*^$|({[\\]/g, '\\$&');
};

And yes, it's disappointing that JavaScript doesn't have a function like this built-in.

查看更多
与风俱净
4楼-- · 2018-12-30 23:36

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.

RegExp.escape = function( value ) {
     return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
查看更多
怪性笑人.
5楼-- · 2018-12-30 23:37

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:

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

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.

查看更多
人间绝色
6楼-- · 2018-12-30 23:45

For anyone using lodash, since v3.0.0 a _.escapeRegExp function is built-in:

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

And, in the event that you don't want to require the full lodash library, you may require just that function!

查看更多
初与友歌
7楼-- · 2018-12-30 23:50
escapeRegExp = function(str) {
  if (str == null) return '';
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
查看更多
登录 后发表回答