i have a url like this. http://localhost:8080/steer/trip/create/3. where in my page i want to get value \"3\" using the jquery . please help me
From: Highlight a button based on location
var pathname = window.location.pathname.split("/");
var filename = pathname[pathname.length-1];
alert(filename);
I am assuming you want to access the parameter value of your controller's action method via jQuery in the client.
In such case, I would rather emit the parameter value as a metadata in a view and query it with jQuery instead of parsing the url itself (you need to decide where to emit, though).
In ASP.NET MVC, if you have a Route that accepts the following pattern: {controller}{action}{param}, http:\myhost\mycontroller\myaction\3 and http:\myhost\mycontroller\myaction?param=3 are equivalent and parsing only one URL pattern will not be sufficient.
You may find examples in jQuery mdatadata plugin useful.
The following is one of the examples in the link above.
<li class="someclass {some: 'data'} anotherclass">...</li>
<script>alert($('li.someclass').metadata().some);</script>
Please disregard this answer if my assumption is not correct.
Plain js
var arr = (window.location.pathname).split("/");
var val = (arr[arr.length-1]);
The value that you require is in val
Here is a easy to read and understand JS function that you can use to retrieve any variable from url.
All you need to do is call this function with name of the variable that you want to filter and it will return the value back to you.
Hope it helps:
function getVarFromURL(varName){
var url = window.location.href;
url = url.substring(url.indexOf('?'));
var urlLowerCase = url.toLowerCase();
varName = varName.toLowerCase();
if (urlLowerCase.indexOf(varName + "=") != -1) {
var value = url.substring(urlLowerCase.indexOf(varName) + varName.length + 1);
if (value.indexOf('&') != -1) {
value = value.substring(0, value.indexOf('&'));
}
return value;
}
else {
return null;
}
}
This will output "3" or basically the whole last segment of the url after the last "/" slash.
var urlsegment = top.location.href.match(/([^\/]+)$/)[1]
It may be overkill here, but for URL parsing, I found this useful:
A jQuery plugin to parse urls and provides easy access to information within them, such as the protocol, host, port, the segments that make up the path and the various query string values.
In your case, this would boil down to something like:
jQuery.url.setUrl("http://localhost:8080/steer/trip/create/3").segment("4");