4

What I want to do is use a variable with window.location.href.indexOf() This is my code right now, I want to be able to shorten it.

var urls  = [
'https://www.example.com/' 
,'https://www.example2.com/' 
,'https://www.example3.com/'  
,'https://www.example4.com/'
,'https://www.example5.com/'
];



// if ((window.location.href.indexOf(""+urls+"") > -1) Does not work
if (
(window.location.href.indexOf("https://www.example.com/") > -1)
|| (window.location.href.indexOf("https://www.example2.com/") > -1)
|| (window.location.href.indexOf("https://www.example3.com/") > -1)
|| (window.location.href.indexOf("https://www.example4.com/") > -1)
|| (window.location.href.indexOf("https://www.example5.com/") > -1)   
) {
//do stuff

}

I've included what I've tried in the code but it doesn not work. javascript and jquery both work for me

Brandon Hellman
  • 103
  • 2
  • 8

5 Answers5

3

You need to use indexOf on array to search the window.location.href within array of urls.

Change

if ((window.location.href.indexOf(""+urls+"") > -1)

To

if (urls.indexOf(window.location.href) > -1)
Adil
  • 146,340
  • 25
  • 209
  • 204
3

Try like this:

if (urls.indexOf(window.location.href) > -1)

instead of

if ((window.location.href.indexOf(""+urls+"") > -1)
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
3

Check like this

if (urls.indexOf(window.location.href) > -1)
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
2
var href = window.location.href; 

//there you need to strip params and leave only domain (https://www.example.com/index.php?q=a convert to https://www.example.com/)

//and then
if (urls.indexOf(href) > -1) {...}
Arūnas Smaliukas
  • 3,231
  • 6
  • 27
  • 46
0

Since you already have the URLs in an array, you can use a loop to test the URLs as follows:

var test = false;
for(var i=0; i < urls.length; i++) {
    test = test || location.href.indexOf(urls[i]) > -1;
}

if( test ) {
    //do stuff
}
PeterKA
  • 24,158
  • 5
  • 26
  • 48