正则表达式值不匹配jquery

时间:2011-02-04 05:47:24

标签: jquery regex

我正在尝试将点击的链接路径与其他链接相匹配。它根本不起作用。这是代码。    我需要将href start与正则表达式链接起来。

 $('#taxonomylist ul li a').click(function() {
        $href = $(this).attr("href");
        $regex = new RegExp("^"+$href);
        $('#taxonomylist ul li').each(function() {
        $href_sub = $("a", this).attr("href");
        if ($href_sub.match($regex))
        {
        $(this).css("display", "block");
        }

       });
       return false;
        });

这是我在萤火虫中得到的:

$href = "/?q=category/activity/test"  
$href_sub = "/?q=category/activity/test/lamp"  
$regex = /^\/?q=category\/activity\/test/  

似乎一切都找不到,但它没有按预期工作。如果我通过正则表达式删除匹配,一切正常(当然没有过滤)。

编辑:

现在它部分有效,只为所有链接分配css属性,而不仅仅是那些匹配值的链接。有没有人看到这个问题?

$('#taxonomylist ul li a').click(function() {
$href = $(this).attr("href");
$regex = new RegExp("^"+$href);
$('#taxonomylist ul li').each(function() {
$href_sub = $("a", this).attr("href");
if ('$href_sub:contains($href)')
{
$(this).css("display", "block");
}

});
return false;
});

2 个答案:

答案 0 :(得分:2)

因为您正在询问正则表达式是否匹配您的字符串。意思是,你的正则表达式至少应该是这样的(基于你的例子):

$regex = /^\/?q=category\/activity\/test\/\w+/

您可能希望使用:contains()选择器。

答案 1 :(得分:1)

check this

使用indexOf(//value to search)进行匹配

希望有所帮助

相关问题