如何使用javascript转义正则表达式特殊字符? [英] How to escape regular expression special characters using javascript?

查看:201
本文介绍了如何使用javascript转义正则表达式特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用java脚本来转义正则表达式特殊字符。我如何实现这一点?任何帮助都应该被理解。

I need to escape the regular expression special characters using java script.How can i achieve this?Any help should be appreciated.

感谢您的快速回复。但我需要逃避正则表达式的所有特殊字符。我已尝试使用此代码,但我无法达到结果。

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.

推荐答案

使用 \ 字符来转义在常规字符内具有特殊含义的字符表达。

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, '\\$&');
}

更新:现在有一项标准化提案这种方法,可能在ES2016中: https://github.com/benjamingr/RegExp.escape

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

更新:上述提案遭到拒绝,因此如果您需要,请继续自行实施。

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

这篇关于如何使用javascript转义正则表达式特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆