【问题标题】:NodeJS Splitting input into multiple strings [duplicate]NodeJS将输入拆分为多个字符串[重复]
【发布时间】: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


    【解决方案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);

    【讨论】:

    • 为什么要使用只包含空格的正则表达式?你可以通过" ".
    • @jfriend00 非常正确。可能是因为我一开始打算尝试找到一些包罗万象的正则表达式。将仅使用 " " 更新答案。
    • 或者只拆分一次:(function(s) {return s.slice(0, 3).concat(s.slice(3).join(" "));})(test.split(" "));
    • @Jason 是的。虽然在美学上我觉得它更丑。
    • 你的单眼线不是碍眼吗? ;)
    猜你喜欢
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2016-01-16
    相关资源
    最近更新 更多