使用 jQuery 获取 url 的最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24379295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get last part of url using jQuery
提问by user3761459
How can I get the last parameter of the URL using jQuery. For example in following URL I want to get 1.
如何使用 jQuery 获取 URL 的最后一个参数。例如在下面的 URL 中我想得到 1。
localhost/x/y/page/1/
I'm trying following
我正在尝试关注
var url = $(location).attr('href');
var parts = url.split("/");
var last_part = parts[parts.length-1];
alert(last_part);
It returns empty value.
它返回空值。
回答by relic
If the "/" is definitely at the end of your url, no matter what.. then just change:
如果“/”肯定在您的网址末尾,无论如何..那么只需更改:
var last_part = parts[parts.length-2]
(use 2 instead of 1) because of ncdreamy's comment.
(使用 2 而不是 1)因为 ncdreamy 的评论。
Also, you don't need var var var var var... just var once and a comma separator:
此外,您不需要 var var var var var... 只需要 var 一次和逗号分隔符:
var url = $(location).attr('href'),
parts = url.split("/"),
last_part = parts[parts.length-2];
回答by Milind Anantwar
You can use:
您可以使用:
hrefurl=$(location).attr("href");
last_part=hrefurl.substr(hrefurl.lastIndexOf('/') + 1)
using jquery
使用jQuery
$(location).attr("href").split('/').pop();
回答by Renish Gotecha
Very Simple Solution
非常简单的解决方案
let url = $(location).attr('href');
let urlKey = url.replace(/\/\s*$/, "").split('/').pop();
console.log(urlKey)
- first get the url
- Replace last
/
from the url - split with
/
and pop the last element
- 首先获取网址
/
从 url替换最后一个- 拆分
/
并弹出最后一个元素
回答by NcDreamy
You're trying to split via '/' so the last / is splitting the url as well. Try this:
您正在尝试通过 '/' 进行拆分,因此最后一个 / 也在拆分 url。尝试这个:
var url = "localhost/x/y/page/1/";
var parts = url.split("/");
var last_part = parts[parts.length-2];
alert(last_part);
回答by Fabián Montero Rodríguez
Don't need to use jQuery. Just use var last = window.location.pathname
不需要使用jQuery。只需使用var last = window.location.pathname
回答by Maulik Gangani
if you don't know if there will be / at the end of url then use @relic solution like this:
如果您不知道 url 末尾是否会有 / 则使用 @relic 解决方案,如下所示:
var url = $(location).attr('href').replace(/\/+$/,''), //rtrim `/`
parts = url.split("/"),
last_part = parts[parts.length-1];
回答by NNR
Think this will help you.
认为这会对你有所帮助。
Here index indicates the split point.
这里 index 表示分割点。
var str="url";
str.split("/")[3]