使用jQuery从URL获取ID

我有这样一个url:

http://www.site.com/234234234 

我需要在/之后获取Id,所以在这种情况下234234234

我怎么能这么容易?

获取/的最后一个索引后的子字符串 。

 var url = 'http://www.site.com/234234234'; var id = url.substring(url.lastIndexOf('/') + 1); alert(id); // 234234234 

它只是基本的JavaScript,不涉及jQuery。

 var url = window.location.pathname; var id = url.substring(url.lastIndexOf('/') + 1); 
 var full_url = document.URL; // Get current url var url_array = full_url.split('/') // Split the string into an array with / as separator var last_segment = url_array[url_array.length-1]; // Get the last part of the array (-1) alert( last_segment ); // Alert last segment 
 var url = "http://www.site.com/234234234" var stuff = url.split('/'); var id = stuff[stuff.length-1]; //id = 234234234 

试试这个javascript

用于从URL获取参数的代码段。 使用javascript从当前窗口位置或静态URL获取URL参数到函数调用的参数。

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; } 

要从上面的静态URL获取参数“id”,请使用以下命令:

 var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true); 

要么

 var idParameter = getUrlParameters("id", "", true); 

使用jQuery URL Parser插件 ,您应该能够这样做:

 jQuery.url.segment(1) 

只因为我可以:

 function pathName(url, a) { return (a = document.createElement('a'), a.href = url, a.pathname); //optionally, remove leading '/' } pathName("http://www.site.com/234234234") -> "/234234234" 

我的url是这样的http://www.default-search.net/?sid=503 。 我想得到503。 我写了以下代码。

 var baseUrl = (window.location).href; // You can also use document.URL var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1); alert(koopId)//503 

如果你使用

 var v = window.location.pathname; console.log(v) 

你只会得到“/”;

试试这个

 var url = "http://www.exmple.com/234234234" var res = url.split("/").pop(); alert(res); 
 const url = "http://www.example.com/1234" const id = url.split('/').pop(); 

试试这个,这要容易得多

输出给出1234