Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing slash from 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>

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.

like image 228
r1853 Avatar asked Jul 02 '15 13:07

r1853


3 Answers

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(/\/+$/, '');
like image 57
type Avatar answered Oct 28 '22 02:10

type


Not what OP asked for exactly, but here are some regex variations depending upon your use case.

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
like image 26
KeshavDulal Avatar answered Oct 28 '22 02:10

KeshavDulal


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

let path = window.location.pathname.replace(/\/+$/, '');
path = path[0] == '/' ? path.substr(1) : path;
like image 23
ArneBuchter Avatar answered Oct 28 '22 02:10

ArneBuchter