How to remove trailing slash from window.location.pathname

帅比萌擦擦* 提交于 2020-02-02 03:57:07

问题


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>

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

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

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

Thanks for any advice offered.


回答1:


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



回答2:


Just use a simple test and remove the trailing slash:

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



回答3:


to remove / before and after, use this (not pretty though)

let path = window.location.pathname.replace(/\/+$/, '');
path = path[0] == '/' ? path.substr(1) : path;


来源:https://stackoverflow.com/questions/31185383/how-to-remove-trailing-slash-from-window-location-pathname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!