Home > database >  cleaner way to check whether or not a the current window.location.href is equal to any of the string
cleaner way to check whether or not a the current window.location.href is equal to any of the string

Time:02-11

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!

CodePudding user response:

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

CodePudding user response:

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.

  • Related