如何从window.location.pathname中删除尾部斜杠

问题描述 投票:3回答:2

我有以下代码允许我在我的网站的桌面和移动版本之间切换,

<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera 
Mini/i.test(navigator.userAgent) ) {
window.location = "http://m.mysite.co.uk";
}
</script>

我最近意识到所有这一切都是将每个人都发送到网站的主页。我挖了一下,想通过修改上面的内容,我可以将特定页面重定向到移动版本,

<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 window.location = "http://m.mysite.co.uk" +  window.location.pathname;
}
</script>

唯一的问题是URL路径末尾的尾部斜杠导致无法识别URL。

有没有办法在Javascript中删除该尾部斜杠?

该站点位于旧的Windows 2003服务器上,因此如果有人建议使用URL Rewrite模块,则为IIS6。

感谢您提供的任何建议。

javascript iis-6 location-href
2个回答
1
投票

只需使用简单的测试并删除尾部斜杠:

var path = window.location.pathname;
path = path[0] == '/' ? path.substr(1) : path;

1
投票

要修复多个尾部斜杠的问题,可以使用此正则表达式删除尾部斜杠,然后使用结果字符串而不是window.location.pathname

const pathnameWithoutTrailingSlashes = window.location.pathname.replace(/\/+$/, '');
© www.soinside.com 2019 - 2024. All rights reserved.