字符串到多个条件的字符串数组

时间:2017-09-28 20:42:25

标签: javascript arrays node.js string split

我有一个用给定参数处理字符串的机器人。以下是我尝试获取命令参数的内容:

parse: function (message, argLength) {
        var words = message.split(" ");
        words.shift(); // Don't return command name in array.
        if (words.length < argLength) // If there is not enough parameters, return null
            return null;
        else if (words.length == argLength) {   // If length is exact same, return     
            return words;
        }
        else { //Otherwise, concenate first ones till it is exact length.
            var concenateString = "";
            var length = words.length - argLength + 1;
            for (var i = 0; i < length; i++) {
                var element = words[0];
                concenateString += " " + element;
                words.shift();
            }
            words.unshift(concenateString);
            return words;
        }
    }

如果参数多于所需参数,它将自动隐藏第一个字符串,因为它被空格分割。 a b c有两个参数&#34; a b&#34; &#34; C&#34;例如。但是如果"被传递,我想在"之间得到单词,而不仅仅是承认第一个单词。

1 个答案:

答案 0 :(得分:1)

在执行任何业务逻辑之前,您可以使用正则表达式在"或单词之间提取任何内容:

&#13;
&#13;
var str = 'one two "three is family"'
var re = /"([^"]+)"|([a-zA-Z0-9]+)/g

console.log(
  str.match( re )
)
&#13;
&#13;
&#13;