0

So say you have some navigation, and you don't/can't use server side code to choose which link is "current". How can you use the first part of the url (as in after the first slash but before any next slash) i.e. (example.com/dashboard/view/16) would return dashboard. Of course there's not always a second slash, it could be (example.com/dashboard). Also before a hash mark i.e. (example.com/dashboard#users) would return dashboard.

Is the best choice to just use location.href and try to write some functions to parse it? Or is there something already made/simpler?

4 Answers 4

1

You should be able to do something like this:

var page = window.location.pathname.split('/')[1];

alert(page);​
Sign up to request clarification or add additional context in comments.

Comments

1

Could the pathname property of the location be of interest?

From w3schools

hash   Returns the anchor portion of a URL
host  Returns the hostname and port of a URL
hostname  Returns the hostname of a URL
href  Returns the entire URL
pathname  Returns the path name of a URL
port  Returns the port number the server uses for a URL
protocol  Returns the protocol of a URL
search  Returns the query portion of a URL

Comments

0

It's easy enough to parse it yourself.

window.location.pathname.slice(1).split('/')[0]

is what you are looking for.

Comments

0
$("a[pathname="+location.pathname+"]")

That jQuery collection will contain all of the links that link to the current page. You could narrow it down to certain elements with a more specific selector and then apply a style to it.

For example:

$("#navigation a[pathname="+location.pathname+"]").css('color', 'red');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.