13

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.

1
  • That's because you're splitting the '/'. There's a / at the end. Try parts.length-2 Commented Jun 24, 2014 at 6:01

7 Answers 7

28

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];
Sign up to request clarification or add additional context in comments.

Comments

9

You can use:

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

using jquery

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

2 Comments

Have you checked? your jQuery solution doesnt seem to work: jsfiddle.net/D2UjM/1
Thats because fiddle href does not have last parameter in it.
5

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

Comments

1

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/

Comments

0

Think this will help you.

Here index indicates the split point.

var str="url";

str.split("/")[3]

4 Comments

This will only work for specific URLs. The author asks for a generic solution.
@Simon - All right but he is new to SO don't please discourage him with -1.
@Code Monkey - Your answer is right but it is static think dynamically and answer it . Thanks
@sudharsan- Thanks for the support.I have to think in innovative way.
0

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

1 Comment

Doesn't that return x/y/page/1/?
0

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];

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.