首页 > 解决方案 > 将部分字符串拆分为变量或数组

问题描述

只是出于好奇,我想知道是否有办法缩短此代码。每个想法都被接受。

const prefix = 'b!',
command = me.content.replace(RegExp(prefix + '\\s'), prefix)
 .slice(prefix.length).split(/\s/)[0],
content = me.content.replace(RegExp(prefix + '\\s'), prefix)
 .slice(prefix.length + command.length).trim(),
args = content.split(/\s/);

me.content.replace(RegExp(prefix + '\s'), prefix)在我的代码中重复,有没有办法在不创建另一个变量的情况下缩短它?

输入: 'b!禁止 @SomeUser 违反规则'

预期输出: 命令:'ban',内容:'@SomeUser 违反规则',参数:['@SomeUser','for','break','the','rules']

标签: javascriptslice

解决方案


const str = "b! ban @SomeUser for breaking the rules";
const [m, cmd, cont] = str.match(/^b!\s+(\S+)\s+(.+)/);


console.log(cmd);
console.log(cont);
// console.log(cont.split(/\s+/))

Regex101.com
PS上的示例和说明,当按空格分割时,将/\s+/连续空格视为一个。
上面给出了您的字符串始终^b! "command"开头。

如果您还想获得@user

const str = "b! ban @SomeUser for breaking the rules";
const [m, cmd, user, reason] = str.match(/^b!\s+(\S+)\s+(@\S+)\s+(.+)/);

console.log(cmd);
console.log(user);
console.log(reason);

Regex101.com上的示例和说明


推荐阅读