Yevgen
Yevgen

Reputation: 797

JavaScript test if url does NOT contain some text

I found many option of checking if the URL contains some text but I am trying to do the opposite.

How can I start a function if the URL DOES NOT contain 'text'?

Here is what I started with that does fire the function but only if the url contains it:

if (document.location.href.indexOf('text') > -1){ 
alert('URL should not have "text" in it');
    }

I tried adding a '!' and a 'NOT' in front of the '(document...' but I guess that's not it.

Upvotes: 6

Views: 33098

Answers (3)

SAURABH
SAURABH

Reputation: 137

It's better to use document.location.pathname.includes('text') simple reason it won't be maintaining the index returned and will be a simple boolean true/false in case of includes In your case simply :-

if(!document.location.pathname.includes('text')){
  //You condition Code goes here
}

Note:- You can always use /text or /text/ instead of test if you know the text will come in the middle of an URL to make it better as othertext will become false in that case.

Upvotes: 0

BastienSander
BastienSander

Reputation: 1838

if (document.location.href.indexOf('text') === -1){ 
    alert('URL should not have "text" in it');
}

Upvotes: 26

EvilVillain
EvilVillain

Reputation: 11

if(document.URL.indexOf("YourText") <= -1){
    "Check"
}

Upvotes: 0

Related Questions