关于替换discord.js中某些单词的代码

时间:2019-07-18 00:24:19

标签: node.js discord.js

我试图让机器人将一个句子中的多个单词替换为另一个单词。

ex:用户将说“今天是美好的一天” 机器人将回答“今天是一个糟糕的夜晚”

在此示例中,单词“ great”和“ day”被替换为单词“ bad”和“ night”。

我一直在寻找以查找类似的代码,但不幸的是,我只能找到“单词黑名单”脚本。

///我尝试使用它进行一些编码,但是我不是node.js的专家,因此代码编写得很糟糕。甚至根本不值得展示。

用户将说出一些句子,然后机器人会识别出该句子中的某些预定单词,并将这些单词替换为我将在脚本中确定的其他单词

1 个答案:

答案 0 :(得分:0)

我们可以结合使用String.replace()Regular Expression来匹配和替换您选择的单个单词。

考虑以下示例:

function antonyms(string) {
  return string
    .replace(/(?<![A-Z])terrible(?![A-Z])/gi, 'great')
    .replace(/(?<![A-Z])today(?![A-Z])/gi, 'tonight')
    .replace(/(?<![A-Z])day(?![A-Z])/gi, 'night');
}

const original = 'Today is a tErRiBlE day.';
console.log(original);

const altered = antonyms(original);
console.log(altered);

const testStr = 'Daylight is approaching.'; // Note that this contains 'day' *within* a word.
const testRes = antonyms(testStr); // The lookarounds in the regex prevent replacement.
console.log(testRes); // If this isn't the desired behavior, you can remove them.