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