0

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.

2
  • 1
    please add some examples of call and the wanted result of it. Commented Sep 28, 2017 at 20:44
  • Let's say I want two parameters; given parameters are "some multi" "word parameters". This code will parse it into an array like this: ["some multi word","parameters"] Commented Sep 29, 2017 at 13:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Will this return an array of strings?
try it I made a snippet
@maloman It is what I actually needed, thanks. I will accept this as the correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.