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

编程入门 行业动态 更新时间:2024-10-24 06:30:15
本文介绍了如何从window.location.pathname中删除尾部斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have the following code that's allowing me to switch between desktop and mobile versions of my website,

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

我最近意识到,所有要做的就是将所有人都发送到该网站的主页.我仔细研究了一下,发现可以通过将上面的内容修改为

I recently realised all that does is send everyone to the homepage of the site. I dug around a bit and figured I could redirect specific pages to the mobile version by amending the above to,

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

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

The only problem with that is the trailing slash on the end of the URL path is causing the URL to not be recognised.

有没有一种方法可以消除Javascript中的尾部斜杠?

Is there a way of removing that trailing slash within the Javascript?

该站点位于旧的Windows 2003服务器上,因此为IIS6,以防有人建议使用URL重写模块.

The site is on an old Windows 2003 server so it's IIS6 in case anyone was going to suggest the URL Rewrite module.

感谢您提供任何建议.

推荐答案

要解决多个斜杠的问题,可以使用此正则表达式删除斜杠,然后使用结果字符串代替window.location.pathname

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

更多推荐

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

本文发布于:2023-11-01 23:09:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杠   尾部   window   location   pathname

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!