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

发布于 2024-11-28 07:22:51 字数 838 浏览 6 评论 0原文

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

这是一个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');
                    }
        });

    })

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

Here is a jsFiddle, below is the code:

<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');
                    }
        });

    })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落花随流水 2024-12-05 07:22:51

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');
        }
    });

});

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

$('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');
        }
    });

});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文