首页 > 解决方案 > 如何检查消息是否以正则表达式开头

问题描述

我正在制作一个不和谐的机器人,现在正在尝试对其进行优化。我不想在我的 if 语句中有很多“或”,有人建议我使用正则表达式。这是我的尝试

if (message.content.toLowerCase().startsWith(/\**(this)/)) {
        message.channel.send('***... ground control to major Tom***');
    }

我正在尝试回复以“this is”或斜体、粗体或两种版本开头的消息。

我曾经有:

if (message.content.toLowerCase().startsWith('this is') || message.content.toLowerCase().startsWith('*this is') || message.content.toLowerCase().startsWith('**this is') || message.content.toLowerCase().startsWith('***this is')) {
        message.channel.send('***... ground control to major Tom***');
}

我可以检查消息是否包含使用正则表达式吗?

谢谢

标签: javascriptdiscord.js

解决方案


const content = message.content;
const regex = /^this is|^\*{1,3}this is/gmi;

if (regex.test(content)) {
    // do something ...
}

推荐阅读