【问题标题】:Last segment of URL in jqueryjQuery中URL的最后一段
【发布时间】:2011-06-13 02:05:33
【问题描述】:

如何获取网址的最后一段?我有以下脚本,它显示点击的锚标记的完整 url:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

如果网址是

http://mywebsite/folder/file

我怎样才能让它在警告框中只显示 url 的“文件”部分?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

Javascript 具有与字符串对象关联的函数 split 可以帮助您:

var url = "http://mywebsite/folder/file";
var array = url.split('/');

var lastsegment = array[array.length-1];

【讨论】:

    【解决方案2】:
    var urlChunks = 'mywebsite/folder/file'.split('/');
    alert(urlChunks[urlChunks.length - 1]);
    

    【讨论】:

      【解决方案3】:

      还有,

      var url = $(this).attr("href");
      var part = url.substring(url.lastIndexOf('/') + 1);
      

      【讨论】:

        【解决方案4】:

        您还可以使用lastIndexOf() 函数来定位您的URL 中最后出现的/ 字符,然后使用substring() 函数返回从该位置开始的子字符串:

        console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
        

        这样,您将避免像 split() 那样创建包含所有 URL 段的数组。

        【讨论】:

        • @oshirowanen,不,但它会从每个 URL 段创建一个数组元素。由于您只对最后一段感兴趣,因此分配许多您永远不会使用的数组元素可能会很浪费。
        • 但是如果 url 变成 admin/store/tour/-1/ 那么它将是 '' 字符串?
        • @Set,也许更好,当然更慢。
        • 如果网址末尾包含/怎么办?
        • 收件人:@Set Kyar Wa Lar Aug 和 @Sнаđошƒаӽ url 末尾包含 / 的解决方案:var url = window.location.href.replace(/\/$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);
        【解决方案5】:

        或者你可以使用正则表达式:

        alert(href.replace(/.*\//, ''));
        

        【讨论】:

        【解决方案6】:
        window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
        

        使用原生的pathname 属性,因为它最简单并且已经被浏览器解析和解析。 $(this).attr("href") 可以返回像 ../.. 这样的值,这不会给你正确的结果。

        如果您需要保留 searchhash(例如 foo?bar#baz 来自 http://quux.com/path/to/foo?bar#baz),请使用:

        window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
        

        【讨论】:

        • 还想添加pathname 去除查询参数,但href 没有。
        【解决方案7】:

        var parts = 'http://mywebsite/folder/file'.split('/');
        var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash
        
        console.log(lastSegment);

        【讨论】:

        • 你能解释一下它是如何工作的吗?据我所知 .pop() 用于删除数组的最后一个元素。但在这里它显示了我的网址的最后一个元素吗!
        • Split 会将您的 url 转换为一个数组,该数组采用 '/' 分隔的 url 的每个部分。因此,最后一段是 url 和随后创建的数组的最后一个元素。
        • 如果网址以“/”结尾,即http://mywebsite/folder/file/,这将不起作用
        • @PeterLudlow 之所以有效,是因为 JS 抽象 "" == false 中的空字符串为假,在这种情况下,它会使用空字符串弹出数组的一部分
        • 旁注:如果 URL 上确实设置了查询参数(例如 .../file?var=value&foo=bar),这将不起作用。该解决方案以更强大和现代的方式解决了这个问题:stackoverflow.com/a/51795122/1123743
        【解决方案8】:

        我知道,为时已晚,但对其他人来说: 我强烈推荐使用PURL jquery plugin。 PURL 的动机是 url 也可以被 '#' 分割(例如:angular.js 链接),即 url 可能看起来像

            http://test.com/#/about/us/
        

            http://test.com/#sky=blue&grass=green
        

        使用 PURL,您可以轻松决定(segment/fsegment)您想要获取哪个段。

        对于“经典”的最后一段,你可以写:

            var url = $.url('http://test.com/dir/index.html?key=value');
            var lastSegment = url.segment().pop(); // index.html
        

        【讨论】:

          【解决方案9】:

          仅使用 javascript 以 Frédéric 的回答为基础:

          var url = document.URL
          
          window.alert(url.substr(url.lastIndexOf('/') + 1));
          

          【讨论】:

            【解决方案10】:

            如果您不担心使用拆分生成额外的元素,那么过滤器可以处理您提到的斜杠问题(假设您的浏览器支持过滤器)。

            url.split('/').filter(function (s) { return !!s }).pop()
            

            【讨论】:

              【解决方案11】:
              // Store original location in loc like: http://test.com/one/ (ending slash)
              var loc = location.href; 
              // If the last char is a slash trim it, otherwise return the original loc
              loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
              var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
              

              targetValue = 一

              如果您的网址看起来像:

              http://test.com/one/

              http://test.com/one

              http://test.com/one/index.htm

              然后 loc 最终看起来像: http://test.com/one

              现在,既然您想要最后一项,请运行下一步以加载您最初想要的值(targetValue)。

              var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
              

              【讨论】:

              • 我可能错过了一些东西,但是使用“test.com/one” loc 最终看起来像:“test.com”。我认为应该是这样的: if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc. substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }
              • 如果searchhash 中出现斜线则失败。
              【解决方案12】:
              var pathname = window.location.pathname; // Returns path only
              var url      = window.location.href;     // Returns full URL
              

              复制自this answer

              【讨论】:

                【解决方案13】:

                正则表达式的另一种解决方案。

                var href = location.href;
                console.log(href.match(/([^\/]*)\/*$/)[1]);
                

                【讨论】:

                  【解决方案14】:
                  window.location.pathname.split("/").pop()
                  

                  【讨论】:

                  • 这正是我想要的。使用 react-router-dom 这是我发现的最干净的解决方案,可以找到 URL 的最后一部分尾随最后一个正斜杠 /console.log(history.location.pathname.split("/").pop())如果有更好的方法我想知道!希望此评论可以引导更多人找到您的答案。谢谢@Dblock247
                  • 旁注:如果 URL 上确实设置了查询参数(例如 .../file?var=value&foo=bar),这将不起作用。该解决方案以更强大和现代的方式解决了这个问题:stackoverflow.com/a/51795122/1123743
                  • @SebastianBarth 这不是在寻找查询字符串参数。对 .pathname 的调用将它们剥离出来,因为重点是获取 url 路径的最后一段,无论是否有查询参数。
                  【解决方案15】:

                  获取当前窗口的最后一段:

                  window.location.href.substr(window.location.href.lastIndexOf('/') +1)

                  【讨论】:

                    【解决方案16】:

                    更新 raddevus 答案:

                    var loc = window.location.href;
                    loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
                    var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
                    

                    将 url 的最后一个路径打印为字符串:

                    test.com/path-name = path-name
                    
                    test.com/path-name/ = path-name
                    

                    【讨论】:

                      【解决方案17】:

                      我认为在执行子字符串之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。

                      window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
                      

                      【讨论】:

                        【解决方案18】:

                        我正在使用正则表达式和拆分:

                        var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?" )[0]

                        最后它会忽略 # 吗? & / 结束 url,这种情况经常发生。示例:

                        https://cardsrealm.com/profile/cardsRealm -> 返回cardRealm

                        https://cardsrealm.com/profile/cardsRealm#hello -> 返回cardRealm

                        https://cardsrealm.com/profile/cardsRealm?hello -> 返回 cardsRealm

                        https://cardsrealm.com/profile/cardsRealm/ -> 返回cardRealm

                        【讨论】:

                          【解决方案19】:

                          如果末尾有/,可以先删除,然后获取url的最后一部分

                          let locationLastPart = window.location.pathname
                          if (locationLastPart.substring(locationLastPart.length-1) == "/") {
                            locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
                          }
                          locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
                          

                          【讨论】:

                            【解决方案20】:

                            如果路径很简单,其他答案可能会起作用,只包含简单的路径元素。但是当它也包含查询参数时,它们就会中断。

                            最好使用URL 对象来获得更强大的解决方案。它是对当前 URL 的解析解释:

                            输入: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'

                            const segments = new URL(href).pathname.split('/');
                            const last = segments.pop() || segments.pop(); // Handle potential trailing slash
                            console.log(last);
                            

                            输出: 'boo'

                            这适用于所有常见的浏览器。只有我们垂死的IE doesn't support that (and won't)。不过,对于 IE,有一个 polyfills 可用(如果你有 care 的话)。

                            【讨论】:

                              【解决方案21】:

                              返回最后一段,不考虑尾部斜杠:

                              var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
                              
                              console.log(val);

                              【讨论】:

                              • 您可能想使用path.sep 而不是文字斜线。见nodejs.org/api/path.html#path_path_sep。这将使您的代码可跨操作系统移植。
                              • 好主意,但它不再适用于浏览器
                              • 好点。我应该说这是命令行脚本/服务器端nodejs的首选。
                              【解决方案22】:

                              我真的不知道正则表达式是否是解决此问题的正确方法,因为它确实会影响代码的效率,但下面的正则表达式将帮助您获取最后一段,它仍然会给您最后一段如果 URL 后跟一个空的 /。我想出的正则表达式是:

                              [^\/]+[\/]?$
                              

                              【讨论】:

                                【解决方案23】:
                                // https://x.com/boo/?q=foo&s=bar = boo
                                // https://x.com/boo?q=foo&s=bar = boo
                                // https://x.com/boo/ = boo
                                // https://x.com/boo = boo
                                
                                const segment = new 
                                URL(window.location.href).pathname.split('/').filter(Boolean).pop();
                                console.log(segment);
                                

                                为我工作。

                                【讨论】:

                                  【解决方案24】:

                                  我知道它很旧,但如果你想从 URL 中获取它,你可以简单地使用:

                                  document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
                                  

                                  document.location.pathname 从当前 URL 获取路径名。 lastIndexOf 获取以下 Regex 的最后一次出现的索引,在我们的例子中是 /.。点表示任何字符,因此,如果 / 是 URL 上的最后一个字符,则不计算在内。 substring 将切断两个索引之间的字符串。

                                  【讨论】:

                                    【解决方案25】:

                                    如果网址是http://localhost/madukaonline/shop.php?shop=79

                                    console.log(location.search); 会带来?shop=79

                                    所以最简单的方法是使用 location.search

                                    您可以查找更多信息herehere

                                    【讨论】:

                                      【解决方案26】:

                                      您可以使用简单的路径(w/0)查询字符串等来做到这一点。

                                      授予可能过于复杂且性能不佳,但我想使用 reduce 来获得乐趣。

                                        "/foo/bar/"
                                          .split(path.sep)
                                          .filter(x => x !== "")
                                          .reduce((_, part, i, arr) => {
                                            if (i == arr.length - 1) return part;
                                          }, "");
                                      
                                      1. 在路径分隔符处拆分字符串。
                                      2. 过滤掉空字符串路径部分(路径中的尾部斜杠可能会发生这种情况)。
                                      3. 将路径部分的数组减少到最后一个。

                                      【讨论】:

                                        【解决方案27】:

                                        使用 RegEx

                                        获取最后一段
                                        str.replace(/.*\/(\w+)\/?$/, '$1');
                                        

                                        $1 表示使用捕获组。在 RegEx (\w+) 中使用创建第一个组,然后将整个字符串替换为捕获组。

                                        let str = 'http://mywebsite/folder/file';
                                        let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
                                        console.log(lastSegment);

                                        【讨论】:

                                          【解决方案28】:

                                          同时获取 URL Last Segment Remove (-) 和 (/) 的最佳方法

                                           jQuery(document).ready(function(){
                                                  var path = window.location.pathname;
                                                  var parts = path.split('/');
                                                  var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash
                                                  lastSegment = lastSegment.replace('-',' ').replace('-',' ');
                                                  jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
                                              
                                              }); 
                                          

                                          【讨论】:

                                            猜你喜欢
                                            • 1970-01-01
                                            • 2017-08-25
                                            • 2013-06-14
                                            • 2016-06-30
                                            • 1970-01-01
                                            • 2015-07-06
                                            • 2012-11-30
                                            • 1970-01-01
                                            • 1970-01-01
                                            相关资源
                                            最近更新 更多