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

时间:2015-10-13 00:33:12

标签: javascript node.js input split

从用户那里获取输入:

!timeout 60 username reason

!timeout,60,用户名永远不会有空格,但可以假设原因通常都有空格。

我希望最终得到:

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

1 个答案:

答案 0 :(得分:1)

对于节省时间的必杀技,我可能会使用一个简单的split和一些放肆的阵列访问:



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);