删除 Javascript/Jquery 中 URL 的最后一部分

Removing final part of URL in Javascript/Jquery

本文关键字:最后 一部分 URL Javascript Jquery 删除      更新时间:2023-09-26

我有一些URL都遵循相同的结构。

https://www.website.com/services/county/town/servicename/brand/

当搜索结果为零时,我们会显示一个按钮,单击该按钮时会运行一个函数来删除 URL 的最后一部分,从而扩展搜索。

例如,如果上述 URL 返回 0 个结果,则单击我们的按钮将加载https://www.website.com/services/county/town/servicename/已从搜索条件中删除brand并扩大结果的机会。

我目前拥有的代码可以工作,但似乎有点黑客。

function expandSearch() {
    var currentURL = window.location.href;
    var parts = currentURL.split("/");
    var lastPart;
    if ( parts.length === 9 )  {
        lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[7].length) + '$';
        window.location.href = currentURL.replace( new RegExp(lastPart), "");
    } else if ( parts.length === 8 ) {
        lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[6].length) + '$';
        window.location.href = currentURL.replace( new RegExp(lastPart), "");
    } else if ( parts.length === 7 ) {
        lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[5].length) + '$';
        window.location.href = currentURL.replace( new RegExp(lastPart), "");
    } else if ( parts.length === 6 ) {
        lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[4].length) + '$';
        window.location.href = currentURL.replace( new RegExp(lastPart), "");
    }
}

搜索可以在任何时间点返回 0 个结果,直到返回整个数据库的https://www.website.com/services/点。

URL 也可能缺少元素,例如它可能有一个county但没有town

有没有更好/更干净的方法来删除最终的 URL 元素并将浏览器重定向到这个新的更广泛的搜索?


我最终得到了的最终工作版本,感谢@ebilgin任何寻找的人:

function expandSearch() {
    var parts = window.location.pathname.substr(1).split("/");
    parts = parts.filter(Boolean); // Remove trailing empty array object
    parts.pop(); // Remove last array object
    window.location.href = "/" + parts.join("/") + "/"; // Go to new Location
}
您可以使用

.pop().join()函数来解决您的问题。

function expandSearch() {
    var parts = window.location.pathname.substr(1);
    var lastCharIsSlash = false;
    if ( parts.charAt( parts.length - 1 ) == "/" ) {
       lastCharIsSlash = true;
       parts = parts.slice(0, -1);
    }
    parts = parts.split("/");
    parts.pop();
    parts = "/" + parts.join("/") + (lastCharIsSlash ? "/" : "");
    window.location.href = parts;
}

如果每个 URI 都有一个尾部斜杠。这是更清晰的版本。

function expandSearch() {
    var parts = window.location.pathname.slice(1, -1).split("/");
    parts.pop();
    window.location.href = "/" + parts.join("/") + "/";
}