0

Im trying to do a redirect if the url is equal to any of the strings in the following array of urls:

So I did the following

function redirectUser() {
  if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
    window.location.replace('https://swish.com/onboard');
  }
}

But this is a bit ugly, so I thought of putting the urls in an array and doing something like this:

function redirectUser() {
  const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
  if (window.location.href === url) {
    window.location.replace('https://swish.com/onboard');
  }
 }
}

Is there any other way to do this? If not, which would be the better option in your opinion? Thanks!

Kenny Quach
  • 225
  • 1
  • 5
  • 18

2 Answers2

1

i think it will help you

   function redirectUser() {
     const urls = ['https://swish.com/login', 'https://swish.com/register', 
      'https://swish.com/overview' ]
         if(urls.includes(window.location.href)){
         window.location.replace('https://swish.com/onboard');
        }
     }  
0

It appears that you already have all the strings statically within the code. So you can try using switch which performance wise is faster than if check here.
If you are reproducing strings via some logic, then you can also opt for Regular Expressions which is even faster. Else, you can stick with arrays.

vat69
  • 123
  • 1
  • 10