I've got a URL like this:
http://www.foo.bar/234234234
I need to grab the Id after /, so in this case 234234234
How can I do this easily?
Get a substring after the last index of /.
var url = 'http://www.site.com/234234234';
var id = url.substring(url.lastIndexOf('/') + 1);
alert(id); // 234234234
It's just basic JavaScript, no jQuery involved.
? and # (and ;) characters and then take the 1st part of it. You don't know if the OP already did this beforehand and omitted it for brevity.try this javascript
Snippet for getting the parameters from URL. Use javascript to get the URL parameters either from current window location or static URL into the argument for the function call.
javascript
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = false;
}
}
if(!returnBool) return false;
}
To get the parameter “id” from above static URL, use the following:
var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true);
or
var idParameter = getUrlParameters("id", "", true);
My url is like this http://www.default-search.net/?sid=503 . I want to get 503 . I wrote the following code .
var baseUrl = (window.location).href; // You can also use document.URL
var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
alert(koopId)//503
If you use
var v = window.location.pathname;
console.log(v)
You will get only "/";
Using the jQuery URL Parser plugin, you should be able to do this:
jQuery.url.segment(1)
Yet another option using the built-in URL interface which worth it when one has more URL specific work to do besides string extraction.
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
const url = new URL('http://www.foo.bar/234234234');
alert(url.pathname.slice(1)); // 234234234
Though the solution @BalusC provided will work for the question's context. But if the url contains some query params like the one below it will not work.
http://www.example.com/234234234?limit=10&sort=desc
In this scenario you can use the following:
const url = "http://www.example.com/234234234?limit=10&sort=desc"
const id = url.substring(url.lastIndexOf('/') + 1, url.indexOf("?"));
Now id will contain only the id number 234234234.
Hope this helps.