Javascript中是否有RegExp.escape函数? [英] Is there a RegExp.escape function in Javascript?

查看:126
本文介绍了Javascript中是否有RegExp.escape函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想用任何可能的字符串创建一个正则表达式。

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);

是否有内置方法?如果没有,人们会用什么? Ruby有 RegExp.escape 。我觉得我不需要自己编写,那里必须有标准的东西。谢谢!

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!

推荐答案

上面链接的功能不足。它无法逃脱 ^ $ (字符串的开头和结尾),或 - ,在字符组中用于范围。

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.

使用此功能:

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.

转义 / 使该函数适合转义在JS正则表达式文字中用于以后的eval的字符。

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.

是的,它是令人失望的是,这不是标准JavaScript的一部分。

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

这篇关于Javascript中是否有RegExp.escape函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆