Xtian
Xtian

Reputation: 3587

Extract last string of a URL

I have a URL like this:

http://www.url/name/something/#/venue

I need to grab the 'venue' from each URL. I have:

var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );

The split breaks up the URL.

I'm not sure how to grab the last part of urlParts.

Upvotes: 1

Views: 357

Answers (6)

dfsq
dfsq

Reputation: 193301

Instead of $(location) why not just use location object and location.hash? Like this:

location.hash.replace('#/', '')

For url like http://www.url/name/something/#/venue it will give you venue.

Upvotes: 1

Ethan Brown
Ethan Brown

Reputation: 27292

To grab the last element in the array urlParts, just use:

var last = urlParts[urlParts.length-1];

As an alternate way to do this, you could do:

var last = currentUrl.substr( currentUrl.lastIndexOf("/")+1 );

Upvotes: 0

The Alpha
The Alpha

Reputation: 146269

var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );
alert(urlParts[urlParts.length-1]);

The fiddle here.

Upvotes: 0

hohner
hohner

Reputation: 11588

You can get it like this:

var url = document.URL.split('#/')[1];

Upvotes: 0

calebds
calebds

Reputation: 26228

Just grab the last element of the urlParts array:

var lastPart = urlParts[urlParts.length - 1];

Upvotes: 1

SLaks
SLaks

Reputation: 888167

urlParts[urlParts.length - 1];

Upvotes: 3

Related Questions