如何从window.location.pathname中删除尾部斜杠
How to remove trailing slash from window.location.pathname
我有以下代码,可以在我的网站的桌面和移动版本之间切换
<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)
相关文章:
- 使用php或javascript从facebook相册URL中删除多余的部分
- RegEx删除空属性?例如,如果(class=“”||class=“”)移除;否则就下课
- 如何删除多行HTML排列中的空白
- 如何从rails中的代码中删除新行( )
- 删除对HTML元素的拖动
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 按顺序添加和删除类
- iframe正在添加标签,需要删除它们
- 如何在HTML输入字段中添加不可删除的后缀
- addData()从最新图表中删除.js 2.1.3-怎么了
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- 删除CKEditor工具栏按钮,但不删除功能
- 当浏览器上的后退按钮到达主页时,我需要删除Class
- 正在删除node.js中已验证的网站
- 正在从页面中删除iframe
- 如何使用jquery或javascript从url中删除带有页码的尾部斜杠
- 什么是正确的javascript RegEx公式删除尾部逗号的字符串
- 如何从window.location.pathname中删除尾部斜杠
- 如何在一行上移动对象并删除旧对象,以便它不会在HTML5 Canvas中留下尾部
- 正在尝试删除尾部文本