Reputation: 519
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
Reputation: 2522
Very Simple Solution
let url = $(location).attr('href');
let urlKey = url.replace(/\/\s*$/, "").split('/').pop();
console.log(urlKey)
/
from the url/
and pop the last elementUpvotes: 5
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
Reputation: 488
Don't need to use jQuery. Just use var last = window.location.pathname
Upvotes: 0
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
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);
Upvotes: 1
Reputation: 303
Think this will help you.
Here index indicates the split point.
var str="url";
str.split("/")[3]
Upvotes: 0
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