Regex in Javascript to trim links
I want to add css class to links (using Javascript) that match begining of link. My links are currently looking like that:
http://localhost/MainApp/User/UserEdit.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1
And I want to check out only the part before id: /MainApp/User/UserEdit.aspx
I already have function that is adding css class to links and it looks like that:
function markActiveLink() {
var path = location.pathname;
var home = "/";
$("a[href='" + [path || home] + "']").parents("li").each(function () {
$(this).addClass("selected");
});
}
value of location.pathname is /MainApp/User/UserEdit.aspx
Question: How can I modify my function markActiveLink() so tha开发者_JAVA技巧t it will mark links even with id after main part of link?
Any help here much appreciated!
Use starts with selector instead of exact selector for href attribute.
Change:
$("a[href='" + [path || home] + "']")
to
$("a[href^='" + [path || home] + "']")
To address issue with the home path selecting all the links change the makeActiveLink to as follows:
function markActiveLink() {
var path = location.pathname;
var links = null;
if(path){
links = $("a[href^='" + path + "']");
} else {
links = $("a[href='/']");
}
links.parents("li").each(function () {
$(this).addClass("selected");
});
}
Not that it is the best solution, but you could use the contains selector:
$("a[href*='" + [path || home] + "']")
精彩评论