Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Simple command line parser in JavaScript

There should be some super cool RegEx, which I can use. However after short research I wasn't able to find it. So, I created a simple function which does the job.

Of course it has its own problems, but works great in my case. It looks like that:

var CommandParser = (function() {
    var parse = function(str, lookForQuotes) {
        var args = [];
        var readingPart = false;
        var part = '';
        for(var i=0; i<str.length; i++) {
            if(str.charAt(i) === ' ' && !readingPart) {
                args.push(part);
                part = '';
            } else {
                if(str.charAt(i) === '\\"' && lookForQuotes) {
                    readingPart = !readingPart;
                } else {
                    part += str.charAt(i);
                }
            }
        }
        args.push(part);
        return args;
    }
    return {
        parse: parse
    }
})();

The CommandParser accepts two arguments. The first one is the string of the command and the second one tells to the parse that maybe some of the parameters are wrapped in quotes. Of course you can skip lookForQuotes. Here are few examples:

>> CommandParser.parse('command param1 param2 param3');
["command", "param1", "param2", "param3"]



>> CommandParser.parse('command param1   param2 param3');
["command", "param1", "", "", "param2", "param3"]



>> CommandParser.parse('command param1 "that\\'s a long parameter" param3');
["command", "param1", ""that's", "a", "long", "parameter"", "param3"]



>> CommandParser.parse('command param1 "that\\'s a long parameter" param3', true);
["command", "param1", "that's a long parameter", "param3"]



>> CommandParser.parse('command param1 "that\\'s a long parameter" "param3 is also a string"', true);
["command", "param1", "that's a long parameter", "param3 is also a string"]

lookForQuotes was added because I had to pass html markup as parameter, which of course contains quotes.

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.