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.
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(/\/+$/, '');
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
to remove / before and after, use this (not pretty though)
let path = window.location.pathname.replace(/\/+$/, '');
path = path[0] == '/' ? path.substr(1) : path;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With