在 RegExp 构建之前清理正则表达式字符串?
我想使用一个字符串来执行全局正则表达式,但它可能包含正则表达式字符。在使用字符串构建正则表达式之前,转义字符串中所有正则表达式字符的最佳方法是什么?
基本上我可能有这样的东西;
var test = 'test.';
var regex = new RegExp(test, 'ig');
我需要“测试”。成为“测试”。所以它不会以意想不到的方式表现。
I want to use a string to perform a global regex, but it might have regex characters in it. What's the best way to escape all regex characters in a string before building a regex with it?
Basically I might have something like this;
var test = 'test.';
var regex = new RegExp(test, 'ig');
I need 'test.' to become 'test\.' so it doesn't behave in unexpected ways.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这会转义以下内容:
#
和.
之间的字符,因此:#$%&'()*+,-.
[
、\
、]
和^
?
、|
,{
,}
...by在每次出现之前添加反斜杠(如
$&
插入匹配的子字符串,g
标志表示替换所有实例。)或者,如果您正在寻找较短的版本,请尝试:
这最终会转义比应有的更多的内容,但不会造成任何损害。
This escapes the following:
#
and.
, so:#$%&'()*+,-.
[
,\
,]
, and^
?
,|
,{
,}
...by prepending a backslash before each occurrence (as
$&
Inserts the matched substring, and theg
flag means to replace all instances.)Alternatively, if you're looking for a shorter version, try:
This will end up escaping a lot more than it should, but it won't harm anything.
这将用转义版本替换所有特殊 RegExp 字符:
This will replace all special RegExp characters with their escaped version: