简体   繁体   English

如何在jQuery中不带空格的正则表达式匹配

[英]How can i match regex without spaces in jquery

I have this regex and its working fine 我有这个正则表达式及其工作正常

var r = new RegExp(page, 'i'); 
$("ul.nav-tabs a").filter(function(){ return $(this).text().match(r) }).parent().addClass("active");

But it don't work if i have 但是如果我有它就行不通

page = useraccount

and text is User Account 文字是User Account

Is there any way to have general regex which matches normal words plus joined words 有什么办法可以使普通正则表达式与普通词和连接词匹配

The way you're doing it is not going to work, because 'user' is always inside of 'useraccount'. 您执行此操作的方式将无法正常工作,因为“用户”始终位于“用户帐户”中。

You can either make it work for your specific use case by working around some issues, or you can do it the right way. 您可以通过解决一些问题使它适合您的特定用例,或者可以以正确的方式来实现。

I suggest adding another field to the links which you can match exactly. 我建议将另一个字段添加到您可以完全匹配的链接中。 Or, even cleaner, to the <li> . 或者,甚至更干净,使用<li> Like this: 像这样:

<ul class="nav-tabs">
    <li data-page="user"><a href="..." >User</a></li>
    <li data-page="useraccount"><a href="..." >User Accounts</a></li>
    ...
</ul>

Then you can just do this in your javascript: 然后,您可以在javascript中执行此操作:

var elements = $("ul.nav-tabs > li").filter(function() {
    return $(this).data('page') == page;
});
elements.addClass("active");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM