user3761459
user3761459

Reputation: 519

Get last part of url using jQuery

How can I get the last parameter of the URL using jQuery. For example in following URL I want to get 1.

localhost/x/y/page/1/

I'm trying following

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

It returns empty value.

Upvotes: 13

Views: 45439

Answers (7)

Renish Gotecha
Renish Gotecha

Reputation: 2522

Very Simple Solution

let url = $(location).attr('href');
let urlKey = url.replace(/\/\s*$/, "").split('/').pop();
console.log(urlKey)
  1. first get the url
  2. Replace last / from the url
  3. split with / and pop the last element

Upvotes: 5

Maulik
Maulik

Reputation: 2991

if you don't know if there will be / at the end of url then use @relic solution like this:

var url =  $(location).attr('href').replace(/\/+$/,''), //rtrim `/`
    parts = url.split("/"),
    last_part = parts[parts.length-1];

Upvotes: 0

Don't need to use jQuery. Just use var last = window.location.pathname

Upvotes: 0

relic
relic

Reputation: 1704

If the "/" is definitely at the end of your url, no matter what.. then just change:

var last_part = parts[parts.length-2]

(use 2 instead of 1) because of ncdreamy's comment.

Also, you don't need var var var var var... just var once and a comma separator:

var url = $(location).attr('href'),
    parts = url.split("/"),
    last_part = parts[parts.length-2];

Upvotes: 28

NcDreamy
NcDreamy

Reputation: 805

You're trying to split via '/' so the last / is splitting the url as well. Try this:

var url = "localhost/x/y/page/1/";
var parts = url.split("/");
var last_part = parts[parts.length-2];
alert(last_part);

http://jsfiddle.net/tEt62/

Upvotes: 1

NNR
NNR

Reputation: 303

Think this will help you.

Here index indicates the split point.

var str="url";

str.split("/")[3]

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can use:

hrefurl=$(location).attr("href");
last_part=hrefurl.substr(hrefurl.lastIndexOf('/') + 1)

using jquery

$(location).attr("href").split('/').pop();

Upvotes: 9

Related Questions