【发布时间】:2015-10-13 00:33:11
【问题描述】:
从用户那里获取输入:
!timeout 60 username reason
!timeout、60 和用户名永远不会有空格,但可以假设原因通常会有空格。
我希望最终得到:
var1 = "!timeout"
var2 = 60
var3 = "username"
var4 = "reason"
【问题讨论】:
标签: javascript node.js input split
从用户那里获取输入:
!timeout 60 username reason
!timeout、60 和用户名永远不会有空格,但可以假设原因通常会有空格。
我希望最终得到:
var1 = "!timeout"
var2 = 60
var3 = "username"
var4 = "reason"
【问题讨论】:
标签: javascript node.js input split
为了节省时间,我可能会使用简单的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);
【讨论】:
" ".
" " 更新答案。
(function(s) {return s.slice(0, 3).concat(s.slice(3).join(" "));})(test.split(" "));