jQuery 获取 URL 的最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17166791/
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
jQuery get last part of URL
提问by huddds
I have a series of pages where I need to get a specific code for a button. I want to put the code which is in the url into a variable with jQuery.
我有一系列页面,我需要在其中获取按钮的特定代码。我想用 jQuery 将 url 中的代码放入一个变量中。
An example URL is www.example.com/folder/code/12345/
一个示例 URL 是 www.example.com/folder/code/12345/
I want to get the number part in a variable called (siteCode)
我想在一个名为 (siteCode) 的变量中获取数字部分
Thanks in advance for any answers.
提前感谢您的任何答案。
jquery / Pseudo code:
jquery/伪代码:
var siteCode;
// start function
function imageCode(){
siteCode // equals number part of URL
$('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
回答by karthi
You can use the following code to get the last part of the url.:
您可以使用以下代码来获取 url 的最后一部分。:
var value = url.substring(url.lastIndexOf('/') + 1);
回答by David says reinstate Monica
I'd suggest:
我建议:
var URI = 'www.example.com/folder/code/12345/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
回答by PSR
var str="url";
str.split("/")[3]
you can use split
你可以使用拆分
回答by Husen
There is one best way to take last part of URL is like following which generally has been used in real implementation.
有一种最好的方法来获取 URL 的最后一部分,如下所示,通常已在实际实现中使用。
There are Some loopholesin previously given answer was:
之前给出的答案有一些漏洞是:
1.Consider what if there is a url like www.example.com/folder/code/12345
(Without '/' forward slash) Than none of the above code will work as per expectation.
1.考虑一下如果有一个像www.example.com/folder/code/12345
(没有'/'正斜杠)这样的网址,上面的代码都不会按预期工作。
2.Consider if folder hierarchy increases like www.example.com/folder/sub-folder/sub-sub-folder/code/12345
2.考虑文件夹层次结构是否增加 www.example.com/folder/sub-folder/sub-sub-folder/code/12345
$(function () {
siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/');
});
var getLastPartOfUrl =function($url) {
var url = $url;
var urlsplit = url.split("/");
var lastpart = urlsplit[urlsplit.length-1];
if(lastpart==='')
{
lastpart = urlsplit[urlsplit.length-2];
}
return lastpart;
}