在Javascript中将URL从位置x拆分到末尾

在Javascript中将URL从位置x拆分到末尾,javascript,Javascript,在Javascript中,我通过location.pathname获取URL的一部分 示例:/cakephp/public/home/Bob/documents 我想将结果从/home开始分割到最后,这样我的结果如下:/home/Bob/documents。需要注意的是,端点不是固定的。在/文档之后可能会出现更多 使用location.pathname.split('/')[4]我得到了Bob。但是如何通过split()方法获取/home/Bob/documents/… 如果使用'/home'作

在Javascript中,我通过
location.pathname
获取URL的一部分

示例:
/cakephp/public/home/Bob/documents

我想将结果从
/home
开始分割到最后,这样我的结果如下:
/home/Bob/documents
。需要注意的是,端点不是固定的。在
/文档之后
可能会出现更多


使用
location.pathname.split('/')[4]
我得到了
Bob
。但是如何通过split()方法获取
/home/Bob/documents/…

如果使用
'/home'
作为
split
参数,则可以将结果数组中的第二个元素附加到字符串
'/home'

'/home' + location.pathname.split('/home')[1]

编辑:

如果字符串中有多个
'/home'
,则需要如下处理:

let splitPath = location.pathname.split('/home')

splitPath.splice(0,1)
然后,您可以通过以下方式获得已处理的路径:


'/home'+splitPath.join('/home')

如果使用
'/home'
作为
split
参数,则可以将结果数组中的第二个元素附加到字符串
'/home'

'/home' + location.pathname.split('/home')[1]

编辑:

如果字符串中有多个
'/home'
,则需要如下处理:

let splitPath = location.pathname.split('/home')

splitPath.splice(0,1)
然后,您可以通过以下方式获得已处理的路径:


'/home'+splitPath.join('/home')
location.pathname.split('/'public')[1]

location.pathname.split('/'public')[1]

此方法处理
/home
字符串在URL中出现多次的情况,例如:

/cakephp/public/home/Bob/documents/pictures/home/bathroom
但同样可以处理其他路径

function getUrl() {
    let splitUrl = location.pathname.split('/home'),
        result = '';

    for (let i = 1; i < splitUrl.length; i++) {
        result += '/home' + splitUrl[i];
    }

    return result;
}
函数getUrl(){ 让splitUrl=location.pathname.split(“/home”), 结果=''; for(设i=1;i此方法处理
/home
字符串在URL中多次出现的情况,例如:

/cakephp/public/home/Bob/documents/pictures/home/bathroom
但同样可以处理其他路径

function getUrl() {
    let splitUrl = location.pathname.split('/home'),
        result = '';

    for (let i = 1; i < splitUrl.length; i++) {
        result += '/home' + splitUrl[i];
    }

    return result;
}
函数getUrl(){ 让splitUrl=location.pathname.split(“/home”), 结果=''; for(设i=1;i我的URL没有固定的结尾。你知道如何动态地进行吗?你所说的“固定端”是什么意思?无论在
/home
之后有多少钱,这都会起作用。好的,我明白了。非常感谢。如果URL看起来是这样的:
/cakephp/public/home/Bob/documents/pictures/home/bathy
,那么数组中的元素会更多?@Magiranu我的原始答案不适用于location.pathname,例如
/cakephp/public/home/Bob/documents/pictures/home/bathy
-编辑后的响应有一个可以处理的版本我的URL没有固定的终端。你知道如何动态地进行吗?你所说的“固定端”是什么意思?无论在
/home
之后有多少钱,这都会起作用。好的,我明白了。非常感谢。如果URL看起来是这样的:
/cakephp/public/home/Bob/documents/pictures/home/bathy
,那么数组中的元素会更多?@Magiranu我的原始答案不适用于location.pathname,例如
/cakephp/public/home/Bob/documents/pictures/home/bathy
-编辑后的响应有一个可以处理的版本那个