javascript 使用RegExp动态创建正则表达式,过滤内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6961615/
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 22:29:09  来源:igfitidea点击:

Using RegExp to dynamically create a Regular Expression, and filter content

javascriptjqueryregexdom-manipulation

提问by Mild Fuzz

I am struggling with using the RegExpobject to allow me to dynamically create an expression, and apply it to a group of elements.

我正在努力使用RegExp对象来允许我动态创建表达式,并将其应用于一组元素。

Here is a jsFiddle, below is the code:

这是一个 jsFiddle,下面是代码:

<div id='selectors'><span>A-F</span><span>G-L</span><span>M-S</span><span>T-Z</span></div>

<a hreh=#>Astring</a>
<a hreh=#>Cstring</a>
<a hreh=#>Xstring</a>
<a hreh=#>Dstring</a>
<a hreh=#>Zstring</a>

$('div#selectors span').click(function(){
        expression = "/^["+$(this).html()+"].*$/";

        rx = RegExp(expression,'i');
        console.log(rx,'expression');
        $("a").each(function(){

                    if($(this).html().match(rx) !== null){
                        $(this).addClass('selected');
                    }
        });

    })

回答by Madara's Ghost

JavaScript automatically adds "/" at the end and the beginning of the expression. Remove them from your string, Example Here

JavaScript 会自动在表达式的末尾和开头添加“/”。从您的字符串中删除它们,示例在这里

$('div#selectors span').click(function () {
    var expression = "^[" + $(this).html() + "].*$";
    var rx = new RegExp(expression, 'i');

    console.log(rx, 'expression');

    $("a").each(function () {
        if ($(this).html().match(rx) !== null) {
            $(this).addClass('selected');
        }
    });

});