首页 > 解决方案 > 如何仅基于路径的一部分重定向 url?

问题描述

让我解释一下我的意思:

我想从https://example.net/category/83745/my-first-post重定向到https://myredirect.net/my-first-post但不考虑 /category/numbers/

目前我正在处理这个:

if(window.location.pathname == '/category/83745/my-first-post')
{
    window.location.href="https://myredirect.net/my-first-post";
}

它工作正常,但正如我所描述的,我需要删除 /category/numbers/ 因为它们可能不同,并且只考虑这部分/my-first-post进行重定向。

提前致谢。

标签: javascriptredirect

解决方案


您可以使用 String 的方法lastIndexOfslice

var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);

推荐阅读