Reputation: 797
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
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
Reputation: 1838
if (document.location.href.indexOf('text') === -1){
alert('URL should not have "text" in it');
}
Upvotes: 26