12

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.

r1853
  • 141
  • 1
  • 1
  • 9

5 Answers5

15

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(/\/+$/, '');
type
  • 366
  • 3
  • 8
9

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
KeshavDulal
  • 3,060
  • 29
  • 30
3

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

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

Just use a simple test and remove the trailing slash:

let path = window.location.pathname;
let lastPathIndex = path.length - 1;
path = path[lastPathIndex] == '/' ? path.substr(0, lastPathIndex) : path;
DvS
  • 1,025
  • 6
  • 11
-1
window.location.pathname.slice(1)
  • 4
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 16 '21 at 06:20
  • This will remove the last character, whatever the last character is; `/hey/` becomes `/hey` but `/hey` becomes `/he` so I wouldn't recommend this – Félix Paradis Sep 16 '21 at 16:20