Reputation: 31
if(window.location.href.indexOf("=38805") > -1
|| window.location.href.indexOf("=38807") > -1
|| window.location.href.indexOf("=38816") > -1
|| window.location.href.indexOf("=38815") > -1
|| window.location.href.indexOf("=38814") > -1
|| window.location.href.indexOf("=38813") > -1
|| window.location.href.indexOf("=38811") > -1
){
do something
}
Basically, I am using a separate css for the pages that contain these strings. I might over 50 pages. Wondering if there is a cleaner way to write this. Put them into an array?
Upvotes: 1
Views: 85
Reputation: 2377
JS some
function, is exactly for stuff like that:
let options = ["=38805","=38807","=38816"]; //...and the others
let link = window.location.href;
if( options.some( option => link.includes(option))){
console.log('yay! =)');
}
You're actually going through your array of options, and asking a question about each of the elements in the array : "Are you present at my URL?".
Then, the some
method will return true (and in this case- active the if
statment ) only if one or more elements in the options
array is answering true
to your includes
question.
And by the way-
JS have another method that cover a similar set of mind. the every
metohd.
This method, as you can understand by its name, will return true only if all the elements in the array is answering true
to your question.
Upvotes: 3
Reputation: 1523
How about something like this to clean it up a bit:
const ids = [38805, 38807, 38811, 38813, 38814, 38815, 38816];
let windowHrefHasId = false;
for (let id of ids) {
if (window.location.href.indexOf('=' + id.toString()) > -1) {
windowHrefHasId = true;
break;
}
}
if (windowHrefHasId) {
// do something
}
Upvotes: 0