获取URL路径字符串中的最后一个值

Get last value in URL path string

本文关键字:最后一个 字符串 URL 路径 获取      更新时间:2023-09-26

给定类似的href

http://localhost:8888/#/路径/某个值/需要这个

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

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

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

你可以试试这个:

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

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

由于您使用的是angularjs,因此可以使用:

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

我要做的是生成一个函数,该函数获取您想要的部分的索引。。这样你就可以随时获得任何零件

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标志,当为true时,你可以返回它。。

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

反转字符串,然后从反转字符串的开头到第一个出现"/"处执行子字符串。

类似这样的东西:

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

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

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

这样path将拥有来自URL 的最后一块文本