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

How to remove trailing slash from window.location.pathname

本文关键字:删除 尾部 pathname window location      更新时间:2023-09-26

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

<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(/'/+$/, '');

这不是OP所要求的,但根据您的用例,这里有一些regex变体。

let path = yourString.replace(/'//g,''); // Remove all slashes from string
let path = yourString.replace(/'//,''); // Remove first slash from string
let path = yourString.replace(/'/+$/, ''); // Remove last slash from string

要删除/之前和之后,请使用这个(不漂亮)

let path = window.location.pathname.replace(/'/+$/, '');
path = path[0] == '/' ? path.substr(1) : path;

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

let path = window.location.pathname;
let lastPathIndex = path.length - 1;
path = path[lastPathIndex] == '/' ? path.substr(0, lastPathIndex) : path;
window.location.pathname.slice(1)