Skip to content

Instantly share code, notes, and snippets.

@achmizs
Last active October 19, 2018 16:46
Show Gist options
  • Save achmizs/a66d93d500620971ad59983e34389e6a to your computer and use it in GitHub Desktop.
Save achmizs/a66d93d500620971ad59983e34389e6a to your computer and use it in GitHub Desktop.
Parsing commandline arguments in JavaScript.
// 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);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment