Dan M
Dan M

Reputation: 3

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>

Upvotes: 0

Views: 45

Answers (1)

Gurtej Singh
Gurtej Singh

Reputation: 3234

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';
}

Upvotes: 1

Related Questions