Search code examples
javascriptreactjsdomecmascript-6href

cleaner way to check whether or not a the current window.location.href is equal to any of the strings in the array


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!


Solution

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