javascript - 如何检查消息是否以正则表达式开头
问题描述
我正在制作一个不和谐的机器人,现在正在尝试对其进行优化。我不想在我的 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***');
}
我可以检查消息是否包含使用正则表达式吗?
谢谢
解决方案
const content = message.content;
const regex = /^this is|^\*{1,3}this is/gmi;
if (regex.test(content)) {
// do something ...
}
推荐阅读
- android - 如何使用 getx 包声明反应式 Firebase 用户
- ios - 如何将stackView固定到视图中,使其从下到上增长
- asp.net - 没有已知的 Anti-CSRF 令牌
- java - 检测 HUGE 文件的编码
- python - 在 Python 中按条件拆分字符串
- python - 不明白这个 numpy 操作如何用于两个数组
- r - 通过检测 col-name 选择单列并保留 colname
- javascript - React 状态根本不会在点击时更新
- python - 用 PyopenVR 在某个坐标处绘制球体的最简单方法是什么?
- prometheus - 如果我们连续 5 分钟没有得到任何指标,PromQL 查询会触发警报