JS check if page/content NOT contains

801 views Asked by At

I want to check if a page contains a specific word. And if it doesn't contain the word, it should to some action.

I only have the code for checking if the word is contained.

var bodyText = document.body.textContent || document.body.innerText;
var msg = "My word";

if (bodyText.indexOf(msg) > -1) {
    setTimeout(function() {
        window.location = "http://contains.word";
    }, 1000);
}

But I want to change it to if it NOT contains it. Any solution?

1

There are 1 answers

2
Zack Tanner On

A simple lookup of the indexOf function should provide you the answer... http://www.w3schools.com/jsref/jsref_indexof.asp

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

If that isn't clear, what you're looking for is if indexOf returns -1.