如何从window.location.pathname中移除末尾的斜杠

12

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

<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 Rewrite模块。

感谢提供的任何建议。

5个回答

15
为了解决多个尾部斜杠的问题,您可以使用此正则表达式来删除尾部斜杠,然后使用生成的字符串代替window.location.pathname
const pathnameWithoutTrailingSlashes = window.location.pathname.replace(/\/+$/, '');

这个答案是为了仅删除最后一个斜杠,下面来自@KeshavDulal的答案更完整。 - Moisés Briseño Estrello

10

不完全符合OP的要求,但以下是一些正则表达式变体,具体取决于您的用例。

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

3

要删除前后的 /,可以使用这个方法(不太美观)

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

1

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

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

这将删除前导斜杠,而不是尾随斜杠。 - Stefan Bajić
哎呀,谢谢你指出了这个明显的错误。我已经更正了答案。@StefanBajić - DvS

-2
window.location.pathname.slice(1)

4
您的回答可以通过提供更多支持性信息来改进。请[编辑]以添加更多详细信息,例如引用或文献,以便他人可以确认您的答案是否正确。您可以在帮助中心找到有关如何撰写良好答案的更多信息。 - Community
这将删除最后一个字符,无论最后一个字符是什么;/hey/ 变成 /hey/hey 变成 /he,所以我不建议这样做。 - Félix Paradis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接