NodeJS将输入拆分为多个字符串

NodeJS Splitting input into multiple strings

本文关键字:字符串 拆分 输入 NodeJS      更新时间:2023-09-26

接受用户的输入:

!timeout 60 username reason

!Timeout、60和username永远不会有空格,但可以假设reason通常会有空格。

我希望以:

结尾
var1 = "!timeout"
var2 = 60
var3 = "username"
var4 = "reason"

为了节省时间,我可能会使用简单的分割和一些假定的数组访问:

var test = "!timeout 60 username reason and then some";
var chunks = test.split(" ");
var timeout = chunks[0];
var time = chunks[1];
var username = chunks[2];
var reason = chunks.slice(3).join(' ');
console.log(timeout, '|', time, '|', username, '|', reason);

或者简单的一行字:

var test = "!timeout 60 username reason and then some";
var result = test.split(" ", 3).concat(test.split(" ").slice(3).join(' '));
console.log(result);