简体   繁体   中英

Highlighting current page in a nav menu?

I looked online to see various approaches of highlighting a current menu navigation with Jquery, and I came across the bit of code below. The code works perfectly but I don't quite understand the second line and I was wondering if one of you could explain it please.

var url = window.location.href;
url = url.substr(url.lastIndexOf("/") + 1);
$("#mainMenu").find("a[href='" + url + "']").addClass("current");

Thanks in advance!

url = url.substr(url.lastIndexOf("/") + 1);

simply grabs the very last segment of the url. For example if the url were

foo.com/module/submodule

it would return submodule

It does this by finding the last index of / , and then passing 1 + that to substr .

From your comment of The part that got me confused was the '+1' at the end , note that substr takes the index at which the substring starts . You don't want to start the substring at / , so 1 is added so that the substring will start at the character immediately after the last / .

And for completeness, the whole remainder of the url is returned since no second parameter is passed to substr. If a second parameter had been passed, then only that number of characters would have been returned.

More info on substr

Check out substr() and lastIndexOf()

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. The calling string is searched backward, starting at 0 by default.

var url returns a string value, and a string is an array of characters. Given that it's an array, each character has a position.

url = url.substr(url.lastIndexOf("/") + 1);

What we're doing is reading the url value and getting a substring of it starting right after the last / of the url, til the end of the value.

To learn more, read up here: http://www.w3schools.com/jsref/jsref_substr.asp

And here's a little fiddle as well: http://jsfiddle.net/gd5Xr/

The second line in your solution trims the full current url from last / .

  • substr() = this trims the given string, in this case - full url.

  • lastIndexOf() = this method brings index integer of the given param. In this case from given url, index number of last / .

  • +1 for substr is just to avoid the last / from new trimmed value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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