11

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

<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 重写模块。

感谢您提供的任何建议。

4

5 回答 5

11

To fix the issue of multiple trailing slashes, you can use this regex to remove trailing slashes, then use the resulting string instead of window.location.pathname

const pathnameWithoutTrailingSlashes = window.location.pathname.replace(/\/+$/, '');
于 2019-04-26T20:23:47.057 回答
5

不是 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
于 2021-06-16T10:57:42.283 回答
3

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

let path = window.location.pathname.replace(/\/+$/, '');
path = path[0] == '/' ? path.substr(1) : path;
于 2019-10-31T11:54:23.497 回答
1

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

let path = window.location.pathname;
let lastPathIndex = path.length - 1;
path = path[lastPathIndex] == '/' ? path.substr(0, lastPathIndex) : path;
于 2015-07-02T13:23:49.297 回答
-1
window.location.pathname.slice(1)
于 2021-09-16T06:05:25.977 回答