javascript - 如何仅基于路径的一部分重定向 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进行重定向。
提前致谢。
解决方案
您可以使用 String 的方法lastIndexOf
和slice
:
var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);
推荐阅读
- anylogic - AnyLogic 事件中的日异常
- c# - 如何使用 LINQ 获取 Json 类型对象的 IDS 列表
- json - Swift 4 - Json 解码器
- css - Boostrap 4 Carousel 视频控件在右侧幻灯片上消失
- vb.net - vb.net 访问文件夹被拒绝
- python - 极慢的计算
- mysql - 如果最后一行的字段满足子句或子查询结果等于0,则插入
- sql-server - 经常断开 mssql 服务器并收到诸如“核心转储”和有时“内存损坏”之类的错误
- spring-boot - 执行器的 Spring Boot 2 升级问题
- ios - 为什么我应该在 iOS 中创建 IPA 之前编辑 Info.plist 和 AppDelegate 文件?