javascript - 将部分字符串拆分为变量或数组
问题描述
只是出于好奇,我想知道是否有办法缩短此代码。每个想法都被接受。
- 我正在尝试使代码的字符尽可能小
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 违反规则'
- 前缀和命令之间可能有一个或多个空格(b!Ban)或没有(b!Ban)。这就是我更换它的原因。还有,前缀是一个变量,我以常量的形式添加它作为例子。
预期输出: 命令:'ban',内容:'@SomeUser 违反规则',参数:['@SomeUser','for','break','the','rules']
解决方案
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上的示例和说明
推荐阅读
- python - phython 中的简单数学测验
- javascript - 如何使用 jasmine spyon 使用特定选择器模拟 ngrx store.pipe
- asp.net-mvc - 如何存储 IEnumerable
在数据库中使用 ASP.NET MVC 标识 - python - 根据对象名称定义类属性
- python - 元素不可交互的硒python3.9
- c# - Teamcity CI Pipeline 无法运行已安装的 dotnet 工具 (sonarscanner)
- reactjs - 触发反应 useEffect
- python - 每次使用 open-cv Python 的任何进程/应用程序访问相机时,是否有方法/方法来检查/返回值?
- php - Livewire 中的 foreach 行为怪异
- hibernate-mapping - 如何将@SqlResultSetMapping 与实体以及一些“额外列”一起使用