robert0
robert0

Reputation: 445

If contains characters then x, else y (Puppeteer)

I have this code which should work in theory, but it doesn't.

I guess there is something that it's missing:

function containsWords(words, word) {
    return words.filter(w => w === word).length > 0;
}

async function grabResult(page) {
    const message = await page.$eval(
        'div > div:nth-child(2)',
        (el) => el.innerText
    );
    
    const username = await page.$eval(
        'child(15) .username',
        (el) => el.innerText
    );

    return {
        message: containsWords(['http', 'https'], message) ? '' : message,
        username: username
    };
};


module.exports = grabResult;

Basically, if there's "http" or "https" in the message, the above code should output an empty message:

{ message: '', username: 'John' }

If none of these words are detected, then it should output the message normally:

{ message: 'message text', username: 'John' }

However, right now even if the message does contain "http" and "https", it still returns the message with those words.

So it either doesn't detect these words, or simply doesn't execute containsWords filter at all.

It simply ignores and outputs every message, regardless of my chosen stop words.

I would appreciate if someone knowledgable would look into the code and tell me what I'm missing here.

thanks.

Upvotes: 0

Views: 314

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13782

In containsWords() you compare the entire message with each word. To check if the message contains any word, you need something like this:

function containsWords(words, message) {
    return words.some(w => message.includes(w));
}

Upvotes: 2

Related Questions