robert0
robert0

Reputation: 445

Puppeteer if string contains X, then do this, else do this

So right now I have this code which grabs the results and it works great:

module.exports = 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, username };
};

console.log(result);

The above code output:

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

What I'm trying to do is before returning the result, to check if the 'message' contains certain words.

If the 'message' contains "http", "https" for example, then it would return empty (which is what I need):

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

If it DOESN'T contain "http", "https", then it would return the 'message' result as my original code.

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

I know there's a command that checks if the text contains x. I found this piece of code on the other thread:

if ((await page.waitForXPath('//*[contains(text(), "Subscription Confirmed")]',30000)) !== null) {
   chk = await page.evaluate(el => el.innerText, await page.$x('//*[contains(text(), "Subscription Confirmed")]'))
   chk = 'Success'
} else { 
   chk = 'Failed'
}

But I'm struggling to combine those two into one code.

Any help would be greatly appreciated.

I'm not a coder, hope I'm clear..

Upvotes: 0

Views: 861

Answers (1)

pavelsaman
pavelsaman

Reputation: 8332

Don't overcomplicate it, you can just write a condition to check what's stored inside message. If you have more values to compare, I can image this is what you're looking for:

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

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

It returns:

{ message: '', username: 'pavelsaman' }

when message equals to http or https. Otherwise it returns non empty message property.

Obviously it also matters what you mean by "contains", perhaps that strict equality should not be there, perhaps you want to check if a string starts with "http" or "https". Then just adjust it accordingly.


The whole file with the exported module could look like this:

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;

Upvotes: 3

Related Questions