JavaScript 中有 RegExp.escape 函数吗? [英] Is there a RegExp.escape function in JavaScript?

查看:36
本文介绍了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 have got to be something standard out there.

推荐答案

另一个答案中链接的功能不足.它无法转义 ^$(字符串的开头和结尾)或 -,它们在字符组中用于范围.

The function linked in another answer is insufficient. It fails to escape ^ or $ (start and end of string), or -, which in a character group is used for ranges.

使用这个功能:

function escapeRegex(string) {
    return string.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.

转义 / 使函数适合转义要在 JavaScript 正则表达式文字中使用的字符以供以后评估.

Escaping / makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation.

因为转义它们中的任何一个都没有缺点,所以转义以涵盖更广泛的用例是有意义的.

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天全站免登陆