简体   繁体   English

简单的jQuery / javascript方法来转义字符串中的特殊字符用于regexp

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

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

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函数,或者我将不得不手动执行此操作(我可能会错过一些东西吗?)

Found a function here : 在这里找到一个功能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM