Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to grab last part of the document.URL?

Tags:

javascript

I am trying to grab the last part of the current url:

URL: http://example.com/test/action

I am trying to grab "action".

The URL is always consistent in that structure. But it may have some extra params at the end.

This is in a rails app using the prototype framework. In rails it would be params[:id].

like image 769
kush Avatar asked Dec 02 '09 18:12

kush


2 Answers

You could simply use .split() on window.location.href, and grab the last entry.

Example:

var lastPart = window.location.href.split("/").pop();
like image 143
Sampson Avatar answered Sep 28 '22 04:09

Sampson


The other answers are fine, however if your url looks like:

http://example.com/test/action?foo=bar

they will fail to give you just "action". To do this you'd use pathname, which contains only the path information exclusive of query string parameters (ie /test/action in this case):

location.pathname.split('/').pop();
like image 43
Roatin Marth Avatar answered Sep 28 '22 04:09

Roatin Marth