【问题标题】:Get last value in URL path string获取 URL 路径字符串中的最后一个值
【发布时间】:2015-06-25 17:28:48
【问题描述】:

给定一个类似的href:

http://localhost:8888/#!/path/somevalue/needthis

如何获取路径字符串中的最后一个值(又名:“needthis”)?

我尝试使用window.location.pathname,它给出“/”。

我也尝试使用 Angular 的 $location,它没有提供最后一个值。

【问题讨论】:

标签: javascript angularjs url


【解决方案1】:

你可以试试这个:

s="http://localhost:8888/#!/path/somevalue/needthis"
var final = s.substr(s.lastIndexOf('/') + 1);
alert(final)

【讨论】:

    【解决方案2】:

    window.location.pathname.split("/").pop()

    【讨论】:

      【解决方案3】:

      由于你使用的是angularjs,你可以使用:

      $location.path().split('/').pop();
      

      【讨论】:

        【解决方案4】:

        我要做的是创建一个函数,它可以索引你想要的部分......这样你就可以随时获得任何部分

        getPathPart = function(index){
            if (index === undefined)
                index = 0;
        
            var path = window.location.pathname,
                parts = path.split('/');
        
            if (parts && parts.length > 1)
                parts = (parts || []).splice(1);
        
            return parts.length > index ? parts[index] : null;
        }
        

        有了这个,你当然可以做出改变,比如 getLastIndex 标志,当它为真时,你可以返回它..

        getPathPart = function(index, getLastIndex){
            if (index === undefined)
                index = 0;
        
            var path = window.location.pathname,
                parts = path.split('/');
        
            if (parts && parts.length > 1)
                parts = (parts || []).splice(1);
        
            if(getLastIndex){
                return parts[parts.length - 1]
            }  
        
            return parts.length > index ? parts[index] : null;
        }
        

        【讨论】:

          【解决方案5】:

          反转字符串,然后从反转字符串的开头到第一次出现“/”做一个子字符串。

          【讨论】:

            【解决方案6】:

            类似这样的:

            var string = "http://localhost:8888/#!/path/somevalue/needthis";
            var segments = string.split("/");
            var last = segments[segments.length-1];
            console.log(last);

            【讨论】:

              【解决方案7】:

              您也可以为此使用正则表达式:

              var fullPath = 'http://localhost:8888/#!/path/somevalue/needthis',
                  result = fullPath.match(/(\w*)$/gi),
                  path = (result)? result[0] : '';
              

              这样path 将获得来自 URL 的最后一段文本

              【讨论】:

                猜你喜欢
                • 2023-03-22
                • 2021-03-24
                • 2019-07-24
                • 1970-01-01
                • 2015-01-17
                • 1970-01-01
                • 2020-04-13
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多