Warning: Undefined array key "lines" in /home/public/wiki.obormot.net/cookbook/gist-embed.php on line 38

Warning: Undefined array key "hl" in /home/public/wiki.obormot.net/cookbook/gist-embed.php on line 52

Warning: Undefined array key "theme" in /home/public/wiki.obormot.net/cookbook/pastebin-embed.php on line 30

Warning: Undefined array key "lines" in /home/public/wiki.obormot.net/cookbook/pastebin-embed.php on line 35

Warning: Undefined array key "hl" in /home/public/wiki.obormot.net/cookbook/pastebin-embed.php on line 51
Parsing Arguments in JavaScript — OborWiki
Reference »

Parsing Arguments in JavaScript

What if you have a string representing a command, entered into a command line (akin to a shell), and you want to parse the whole thing, tokenizing arguments and separating out flags, etc.… in JavaScript? Do you need to install some fancy package off npm? No, not really.

This code is released under the MIT License.

// Utility methods. Makes the code more readable.
Array.prototype.contains = function (element) {
    return (this.indexOf(element) !== -1);
}
String.prototype.hasPrefix = function (prefix) {
    return (this.lastIndexOf(prefix, 0) === 0);
}

    var parts = [ ], flags = [ ];

    // Tokenize.
    var re = /(?:”([^”]+)”|(\S+))/g;
    var matches;
    while ((matches = re.exec(enteredText)) !== null)
        parts.push(matches[1] || matches[2]);

    // Filter out and set aside flag-bearing tokens.
    let flagTokens = parts.filter(part => part.hasPrefix(″-”));
    parts = parts.filter(part => !part.hasPrefix(″-”));

    // Construct list of unique flags.
    flagTokens.forEach(token => {
        if (token.hasPrefix(″--”) && !flags.contains(token.substring(2)))
            flags.push(token.substring(2));
        else
            [...token.substring(1)].forEach(c => {
                if (!flags.contains(c)) flags.push(c);
            });
    });