Matthew
Matthew

Reputation: 15642

jquery/javascript - parsing url to see if you're on a certain page

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?

Upvotes: 0

Views: 883

Answers (4)

Cristian Sanchez
Cristian Sanchez

Reputation: 32097

$("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');

Upvotes: 0

some
some

Reputation: 49582

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

Upvotes: 1

user113716
user113716

Reputation: 322462

You should be able to do something like this:

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

alert(page);​

Upvotes: 1

PleaseStand
PleaseStand

Reputation: 32052

It's easy enough to parse it yourself.

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

is what you are looking for.

Upvotes: 0

Related Questions