teresawithoutah teresawithoutah - 1 year ago 55
Javascript Question

how to check if strings of an array are on page pure js

Trying to make a chrome extension where if certain words are on the feed/page it'll print a message in console

heres my current code:

// Checking page title
if (document.title.indexOf("Twitter") != -1) {

//Checks if selected text is on page
if (document.documentElement.innerText.indexOf('enjoys') > -1) {

//if selected text is on page, print this
console.log("it works!");
} else {

// if selected text is not on page, print this
console.log("selected text is not on page");
} else {

//if not on twitter print this
console.log("title is not twitter");

this code works fine but it's limited to only one word which, as you can see above, is currently the word enjoys. I want to change it so that I can replace the one word with an array with several words/strings.

so lets say I have the array spoiled:

var spoiled = ["terrible", "hit", "pain"];

I want my extension to check if all those words in spoiled are on my twitter page.

in pure JS, how do I do that?

Answer Source

You could iterate, and use every() to check for all the words

var spoiled = ["terrible", "hit", "pain"];

var result = spoiled.every(function(word) {
    return document.documentElement.innerText.indexOf(word) > -1;

if (result) { // all exists }