Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

javascript - 如何使用javascript转义正则表达式特殊字符? [重复](How to escape regular expression special characters using javascript? [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

Is there a RegExp.escape function in Javascript?(Javascript中是否有RegExp.escape函数?) 13 answers(13个答案)

I need to escape the regular expression special characters using java script.How can i achieve this?Any help should be appreciated.(我需要使用java脚本转义正则表达式特殊字符。如何实现这一点?任何帮助都应该被理解。)

Thanks for your quick reply.But i need to escape all the special characters of regular expression.I have try by this code,But i can't achieve the result.(感谢您的快速回复。但我需要逃避正则表达式的所有特殊字符。我已经尝试了这段代码,但我无法达到结果。) RegExp.escape=function(str) { if (!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\' ]; arguments.callee.sRE = new RegExp( '(\' + specials.join('|\') + ')', 'gim' ); } return str.replace(arguments.callee.sRE, '\$1'); } function regExpFind() { <%--var regex = new RegExp("\[munees\]","gim");--%> var regex= new RegExp(RegExp.escape("[Munees]waran")); <%--var regex=RegExp.escape`enter code here`("[Munees]waran");--%> alert("Reg : "+regex); } What i am wrong with this code?Please guide me.(这段代码我错了什么?请指导我。)   ask by Muneeswaran Balasubramanian translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the \ character to escape a character that has special meaning inside a regular expression.(使用\字符来转义正则表达式中具有特殊含义的字符。)

To automate it, you could use this:(要自动化它,您可以使用:) function escapeRegExp(text) { return text.replace(/[-[]{}()*+?.,\^$|#s]/g, '\$&'); } Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape(更新:现在有一个标准化此方法的提议,可能在ES2016中: https//github.com/benjamingr/RegExp.escape) Update : The abovementioned proposal was rejected, so keep implementing this yourself if you need it.(更新 :上述提案被拒绝,因此如果您需要,请继续自行实施。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...