简单的 jQuery / javascript 方法来为正则表达式转义字符串中的特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5306095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:43:40  来源:igfitidea点击:

Simple jQuery / javascript method to escape special characters in string for regexp

javascriptjqueryregex

提问by John Hunt

I'm performing a regular expression using the match() method on a string that comes from the user and could contain anything, including $^'s etc.. so I need to escape those characters before this happens.

我正在使用 match() 方法对来自用户的字符串执行正则表达式,并且可以包含任何内容,包括 $^'s 等。所以我需要在发生这种情况之前转义这些字符。

Is there a common function in jQuery to do this, a well known javascript function or am I going to have to do it manually (with the chance I might miss something?)

jQuery 中是否有一个通用函数来执行此操作,一个众所周知的 javascript 函数,或者我将不得不手动执行此操作(我可能会错过某些内容?)

回答by John Hunt

Found a function here:

在这里找到了一个函数:

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