简体   繁体   中英

Script issue about “ link redirecting ”

Here's the script:

<script>
if(document.location.href.indexOf('https://thedomain.com/collections/all?sort_by=best-selling') > -1) { 
document.location.href = 'https://thedomain.com/pages/bestsellers';
}
</script>

Question is, how can i make the code so that when i put https://thedomain.com/////////////////////////////////////////collections/all?sort_by=best-selling

it would still send me to the designated link. Or whenever i duplicate any of the "/" "?" "_" "=" "-" characters. When i do duplicate those characters in my website it doesn't redirect to the page i want it to go ( or it doesn't do it automatically)

Bottom line is i don't want to be forced to do this (its inefficient):

<script>
if(document.location.href.indexOf('https://thedomain.com/////////////////////////////////////////collections/all?sort_by=best-selling') > -1) { 
document.location.href = 'https://thedomain.com/pages/bestsellers';
}
</script>

Just use the following reg-ex to remove extra slashes from your URL :

var correctURL= document.location.href.replace(/([^:]\/)\/+/g, "$1"); 
//removes every slash that follows after a character that is not : and then a slash.

Now you can validate against this url:

if(correctURL.indexOf('https://thedomain.com/collections/all?sort_by=best-selling') > -1) { 
    document.location.href = 'https://thedomain.com/pages/bestsellers';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM