pathname中删除尾部斜杠

pathname中删除尾部斜杠

本文介绍了如何从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 = "http://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 = "http://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中删除尾部斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:21