我有以下代码可以让我在网站的桌面版和移动版之间切换,
<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 服务器上,因此它是 IIS6,以防有人建议使用 URL 重写模块。
感谢您提供的任何建议。
最佳答案
要解决多个尾部斜杠的问题,您可以使用此正则表达式删除尾部斜杠,然后使用生成的字符串而不是 window.location.pathname
const pathnameWithoutTrailingSlashes = window.location.pathname.replace(/\/+$/, '');
关于javascript - 如何从 window.location.pathname 中删除尾部斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31185383/