Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last part of url using jQuery

Tags:

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.

like image 885
user3761459 Avatar asked Jun 24 '14 05:06

user3761459


People also ask

How do I find the last part of a URL?

We identify the index of the last / in the path, calling lastIndexOf('/') on the thePath string. Then we pass that to the substring() method we call on the same thePath string. This will return a new string that starts from the position of the last / , + 1 (otherwise we'd also get the / back).

How do I remove the last URL?

First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want.

How can I get the last part of a URL in PHP?

')) $uri = substr($uri, 0, strpos($uri, '? ')); $url = trim($uri, '/');


1 Answers

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];
like image 52
relic Avatar answered Sep 25 '22 20:09

relic