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

Tom*_*hen 3 javascript jquery if-statement function

我有一些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), "");
    }
}
Run Code Online (Sandbox Code Playgroud)

搜索可以在任何点返回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

}
Run Code Online (Sandbox Code Playgroud)

ebi*_*gin 5

您可以使用.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;
}
Run Code Online (Sandbox Code Playgroud)

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

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