将类添加到regex jquery
我有这个
if( window.location.href == "http://localhost:3000/categories") { $("#container ul #all_categories a.categories-menu").css("font-weight","bold"); } });
但我有一个url:
http://localhost:3000/username/boards
username是动态用户名,例如
http://localhost:3000/michael-21/boards http://localhost:3000/Richard_10/boards http://localhost:3000/Mary.50/boards
并为每个用户更改。
如何使用相同的function但使用此最后一个URL?
谢谢
您不需要RegEx。 以下方法更容易,也更易于维护(在将页面移动到生产环境时,您不必更改代码中的URL):
location.pathname.indexOf('/boards', 1) !== -1
以前也会匹配/me/not/boards
。 如果你不想那样:
var index = location.pathname.indexOf('/boards', 1); index !== -1 && location.pathname.lastIndexOf('/', index-1) === 0
最后,RegEx方法:
/^\/[^/]+\/boards/.test(location.pathname)
实施例
if( /^\/[^/]+\/boards/.test(location.pathname) ) { $("#container ul #all_categories a.categories-menu").css("font-weight","bold"); } });