I tried the 2 solutions posted here to detect a specific words and they do work:
Solution 1
const badMessages = ["bad", "worst"];
badMessages.forEach((word) => {
if (message.content.includes(word)) {
message.reply("Detected.");
}
})
Solution 2
const badMessages = ["bad", "worst"];
for(var i=0; i<badMessages.length; i ) {
if (message.content.includes(badMessages[i])) {
message.reply("Detected.");
}
}
However, the condition triggers even when the word in the array for example bad is mixed with other words like "badge". How do I detect a specific word by itself which should trigger for the exact "bad" word only and not trigger when it is mixed with other words like badge.
CodePudding user response:
You can try to wrap all bad words with spaces, so it will only search for those specific words separated by spaces?
Better solution would be to use a regular expression like what has been suggested here.
CodePudding user response:
you can use the regular expression \b(bad|wrong)\b
https://regex101.com/r/cxHSki/1
const messages = [
'bad bads man wrong',
'bads man wrong',
'abad man wrong',
'abad man wrongs',
'abad man awrong',
'bad man',
'wrong man',
'badge text'
]
const badMessages = ["bad","wrong"];
messages.forEach(x => {
const regex = RegExp(`(\\b)(${badMessages.join('|')})(\\b)`, 'g')
//const regex = RegExp(`(\\b)(${badMessages.join('|')})(\\b)`, 'gi') for case insensitive
const isMatch = regex.test(x)
console.log(isMatch)
})