Jenny
Jenny

Reputation: 919

If url has index of x or y then do not do the following

I think I am having trouble with my syntax on this. I want it to say if the url has indexof 425 or if the url has an indexof 297 do not run the following. This works for doing just one:

    if (document.location.href.indexOf('425') === -1){ 

But when I try to add the second indexof it doesnt work, here is what I have tried

//attempt 1
    if (document.location.href.indexOf('425') === -1 || document.location.href.indexOf('297') === -1){ 

}
//attempt 2
    if ((document.location.href.indexOf('425')) === -1 || (document.location.href.indexOf('297')) === -1)){ 

}

Upvotes: 1

Views: 65

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386670

You need a logical AND &&, because both parts have to be true

if (
    document.location.href.indexOf('425') === -1 &&
    document.location.href.indexOf('297') === -1
) { 
    // ...
}

For more than one value, you could take an array with the unwanted parts and use Array#every for checking.

if ['425', '297'].every(s => !document.location.href.includes(s))) {
    // ...
}

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074949

I want it to say if the url has indexof 425 or if the url has an indexof 297 do not run the following.

Or to put it another way, if the url doesn't have 425 and doesn't have 297, do the following:

if (document.location.href.indexOf('425') === -1 && document.location.href.indexOf('297') === -1){

=== -1 means it wasn't found.

But these days, you can use includes (polyfilling for IE if you need to support IE):

if (!document.location.href.includes('425') && !document.location.href.includes('297')){

Upvotes: 3

Related Questions