Reputation: 85
I am trying to make my Discord bot replace various words in a message with other words, but I can't seem to figure out how to do it for more than 1 word.
Let me give an example:
I want to replace the '!say' with nothing
I want to replace 'llama' with 'ogre'
I want to replace 'john' with 'johnny'
So, I want the bot to replace these words with the other words. But I can only figure it out with doing one replacement, otherwise it repeats the message over and each with the different change.
Here's the code I got at the moment for this
client.on("message", message => {
if (message.content.startsWith("!say")) {
message.channel.sendMessage("I say: " + message.content.replace('!say ','' + '\n'))
};
});
Anyone know how? Sorry if this is super confusing :(
Upvotes: 1
Views: 2040
Reputation: 370729
I'd make an object whose keys are the words you want to replace, and whose values are their replacements. Then you can construct a regular expression by joining all keys together, and use a replacer function to look up the appropriate replaced value on the object:
const replacements = {
'!say': '',
llama: 'ogre',
john: 'johnny'
};
const pattern = new RegExp(Object.keys(replacements).join('|'), 'g');
client.on("message", message => {
const replacedText = message.content.replace(pattern, key => replacements[key]);
// use replacedText
});
const replacements = {
'!say': '',
llama: 'ogre',
john: 'johnny'
};
const pattern = new RegExp(Object.keys(replacements).join('|'), 'g');
const input = '!say foo bar llama baz john buzz';
const replacedText = input.replace(pattern, key => replacements[key]);
console.log(replacedText);
Upvotes: 1