Reputation: 35
I'm trying to check if a message includes a certain word. Now, I know it's message.content.includes
, but mine is a little bit different and it's not working.
Heres the code:
client.on('message', (message) => {
// Right here is where it's not working. If I remove the includes part,
// it can detect the word if it's by its self. But if I'm saying
// something like "Hahaha Heck" it won't see it.
if (/^H[A-Za-z]{2}k$/.test(message.content.includes)) {
message.delete();
message.reply('Okay');
message.member.roles.add('805088740737417256');
}
});
Does anybody know the solution to this?
(If you're wondering what the /^H[A-Za-z]{2}k$/
part is the regex pattern and it looks for any words that fit with anything between the 2 letters H and k.)
Upvotes: 2
Views: 1289
Reputation: 23170
message.content
is a string and that includes
method is actually String.includes
, a built-in JavaScript method that checks if one string can be found within another string. You can't use regular expressions as search strings.
If you want to check strings using regexes, you can either use RegExp.test
or the String.match
method. RegExp.test
will return true
if there is a match, and false
otherwise. If you're using String.match
, it will return an array if there are matches, or null
otherwise.
As Randy Casburn mentioned, your regex doesn't work because /^H[A-Za-z]{2}k$/
checks if the string starts with a H
and ends with a k
. You can use word boundaries instead. The word boundary \b
matches positions where one side is a word character. Try to replace the ^
and $
anchors with the \b
and it will work: /\bH\w{2}k\b/
.
Check out the working examples below:
Using .test()
client.on('message', (message) => {
if (message.author.bot) return;
if (/\bH\w{2}k\b/.test(message.content)) {
message.delete();
message.reply('Okay');
message.member.roles.add('805088740737417256');
}
});
Using .match()
client.on('message', (message) => {
if (message.author.bot) return;
if (message.content.match(/\bH\w{2}k\b/) !== null) {
message.delete();
message.reply('Okay');
message.member.roles.add('805088740737417256');
}
});
Upvotes: 1
Reputation: 14175
Use word boundaries rather than ^
and &
. Those two search from the beginning of the string all the way to the end. Word boundaries on the other hand will search each individual "word".
If you want to find all of them, you'll need to use the greed flag and .matchAll()
const strs = [
"Heck! I hit my table on accident",
"What the Heck",
"Hank is not Heckle, but Hank Heck is cool"
];
const regex = /\bH\w{2}k\b/;
strs.forEach(s=>console.log(s.match(regex)));
Upvotes: 2