【问题标题】:How can I replace all with a variable?如何用变量替换所有内容?
【发布时间】:2020-07-09 03:29:22
【问题描述】:

我正在为我的 Discord.js 机器人制作过滤器。如果字符不在英文字母表中,则应将其删除,以便过滤器检查字符串中的单词是否被过滤。

const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

bot.on("message", message => {
if (message.author.bot) return;
if (message.channel.type == "dm") return;

var args = message.content;
var argsnt = message.content.toLowerCase().toString().split("");
var str = "";

// Checking each character.

  argsnt.forEach(element => {
  if (!alphabet.includes(element) && !str.includes(element)) {
    str = str + element;
    console.log("add");
    console.log(str);
  }
});

// Removing the characters.

const search = str;
const replacer = new RegExp(search, 'g');
args = args.replace(replacer, "");

message.reply(args);

});

问题:

如果你有两个不同的符号,它只会删除其中一个符号。

如果它是像括号一样打开或关闭的东西,它会给我一个关于正则表达式的错误。

注意:

我从上面的代码中收到的唯一错误是正则表达式错误。一个多星期以来,我已经研究和测试了很多东西,但没有找到任何解决方案。我现在不想尝试最快的方法。我只是想找到一些有用的东西。

【问题讨论】:

  • 你能举一些例子吗?
  • 一个符号:Tes!t > 测试两个符号:T!es@t > T!es@t

标签: node.js discord.js


【解决方案1】:

您实际上可以使用 RegEx .replace() 执行此操作,如下所示:

args.toLowerCase().replace(/[^a-z]/g, '')

如果您使用它,请确保 args 保留为消息内容,而不是拆分消息内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 2018-05-12
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多