views:

125

answers:

3

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

+1  A: 

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

Example:

var lastPart = window.location.href.split("/").pop();
Jonathan Sampson
or `Array#pop()`
Chetan Sastry
Good suggestion, Chetan. Updated my response.
Jonathan Sampson
+3  A: 

use document.location.href.substring( document.location.href.lastIndexOf( '/' ) );

Jacob Relkin
I'd go with `location.pathname` instead of `location.href` if you don't want to grab the query part of the URL; also, MDC recommends to use `window.location` instead of `document.location` for compatibility reasons
Christoph
A: 

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();
Roatin Marth