0

I'm making a bot that will ping me if a certain phrase gets said in my discord. Currently I am using

if(message.content.toLowerCase() === 'word')

How can I make it so it will detect "word" in any sentence? New to coding so I just followed a guide and after a few hours I couldn't figure it out. I only got it to ping me if only "word" was said and nothing else.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Kwehh
  • 9
  • 1
  • regex is your friend. – John Manko Jul 10 '22 at 19:31
  • So is `includes()`. Like `if (message.content.toLowerCase().includes('word'))`. Next time you should [do some research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) first... – Zsolt Meszaros Jul 10 '22 at 20:04
  • Does this answer your question? [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – Zsolt Meszaros Jul 10 '22 at 20:05

1 Answers1

0

A simplistic solution is:

function contains(content, word) {
    return (content.toLowerCase().indexOf('word') >= 0);
}

console.log(contains("This is the word!")); //true
console.log(contains("This is WordPress")); //true
console.log(contains("Something")); //false

As you can see, the second example is incorrect, because WordPress semantically differs from word. So, if it's not enough to find the word, but we want to isolate it as well, then we can do something like this:

function contains(content, word) {
    let pattern = new RegExp("[^a-z]" + word + "[^a-z]");
    return (pattern.test(content.toLowerCase()));
}

console.log(contains("This is the word!", "word")); //true
console.log(contains("This is WordPress", "word")); //true
console.log(contains("Something", "word")); //false

In this second example, I prepend and append [^a-z], which means "not a letter"

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175