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 pro开发者_如何学Ctotype framework. In rails it would be params[:id].
You could simply use .split() on window.location.href
, and grab the last entry.
Example:
var lastPart = window.location.href.split("/").pop();
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();
use document.location.href.substring( document.location.href.lastIndexOf( '/' ) );
with jquery :
var idFromUrl = window.location.href.split("/").pop();
$('#various3').attr('href', $('#various3').attr('href').replace('placed_id', idFromUrl));
Below is my working javascript solution.Hope it helps some one and hence posting.This solution is to retrieve last part of url leaving the generally not needed query string part.It helps to identify from which page the visit happened and write logic based on that.
var url = document.referrer;
var start = url.lastIndexOf("/") + 1;
var len = url.indexOf("?");
if (len > 0)
url = url.substring(start, len);
else
url = url.substring(start);
精彩评论