String To String Array With Multiple Conditions

I have a bot which processes strings with given arguments. Here is what I've tried to get parameters of command:

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

If there are more parameters than required, it will automatically concenate first strings since it is split by spaces. a b c with two parameters to "a b" "c" for example. But if "'s are passed, I want to get words between "'s, not only conceding first ones.

Upvotes: 0

Views: 104

Answers (1)

maioman
maioman

Reputation: 18744

Before doing any business logic you could use a regex to extract anything between " or words:

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

console.log(
  str.match( re )
)

Upvotes: 1

Related Questions