简体   繁体   English

jQuery 获取 URL 的最后一部分

[英]jQuery get last part of URL

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

您可以使用以下代码来获取 url 的最后一部分。:

var value = url.substring(url.lastIndexOf('/') + 1);

I'd suggest:我建议:

var URI = 'www.example.com/folder/code/12345/',
    parts = URI.split('/'),
    lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();

JS Fiddle demo . JS小提琴演示

var str="url";

str.split("/")[3]

you can use split你可以使用拆分

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 loopholes in 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这样的 url(没有 '/' 正斜杠) 上面的代码都不会按预期工作。

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

Also try using 也尝试使用

var url = "www.example.com/folder/code/12345";
  var checkExt = /\d$/i.test(url);
  if (checkExt) {
      alert("Yup its a numeric");
  } else {
      alert("Nope");
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM