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

3
我有一些URL,它们都遵循相同的结构。
当搜索结果为零时,我们会显示一个按钮,点击该按钮运行一个函数以删除URL的最后一部分,从而扩展搜索范围。
例如,如果上面的URL返回0个结果,则单击我们的按钮将加载https://www.website.com/services/county/town/servicename/,从搜索条件中删除了brand,并扩大了结果的机会。
我目前的代码可以工作,但似乎有点像一个hack。
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 也可能缺少某些元素,例如它可能具有县级但没有城镇。
是否有更好/更清晰的方法来删除最终的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

}
1个回答

6
您可以使用 .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("/") + "/";
}

谢谢您的回复,如果URL中没有尾随斜杠给我额外的空数组对象,那么这将完美地工作。["http:", "", "website.com", "services", "county", "servicename", ""]。有什么办法可以从数组中仅删除最后一个对象吗?我猜我可以使用pop()两次,但这似乎又有点像黑客攻击 :) - Tom Pinchen
@TomPinchen 实际上,location.pathname比location.href更准确。你可以使用我的解决方案的新版本。 - ebilgin
这个干净多了。尽管它似乎仅仅是从我的URL中移除了尾随斜线。你知道为什么会这样吗? - Tom Pinchen
谢谢你的帮助 - 我通过对部件运行过滤器来检查空数组并将其删除,然后使用你的第一个 parts.pop() 版本,成功让它工作了! - Tom Pinchen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接