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

Javascript 如何从window.location.pathname中删除尾部斜杠,javascript,iis-6,location-href,Javascript,Iis 6,Location Href,我有以下代码,允许我在桌面和移动版本的网站之间切换 <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> 如果(/Android | webOS | i

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

<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>

如果(/Android | webOS | iPhone | iPad | iPod |黑莓| IEMobile | Opera
Mini/i.test(navigator.userAgent)){
window.location=”http://m.mysite.co.uk";
}
我最近意识到,这样做只是把每个人都发送到网站的主页上。我仔细研究了一下,认为我可以通过修改上述内容将特定页面重定向到移动版本

<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>

if(/Android | webOS | iPhone | iPad | iPod | BlackBerry | IEMobile | Opera Mini/i.test(navigator.userAgent)){
window.location=”http://m.mysite.co.uk“+window.location.pathname;
}
唯一的问题是URL路径末尾的尾随斜杠导致无法识别URL

有没有办法删除Javascript中的尾部斜杠

该网站位于旧的Windows2003服务器上,因此它是IIS6,以防有人建议使用URL重写模块


感谢您提供的任何建议。

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

var path = window.location.pathname;
path = path[0] == '/' ? path.substr(1) : path;

要解决多个尾部斜杠的问题,可以使用此正则表达式删除尾部斜杠,然后使用生成的字符串而不是
window.location.pathname

const pathnameWithoutTrailingSlashes = window.location.pathname.replace(/\/+$/, '');

要删除/之前和之后,请使用此选项(但不美观)


这并不是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

为我工作!Thx@type。
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