Skip to content

Instantly share code, notes, and snippets.

@kyoh86
Last active August 29, 2015 14:13
Show Gist options
  • Save kyoh86/055285d960259cb4b2de to your computer and use it in GitHub Desktop.
Save kyoh86/055285d960259cb4b2de to your computer and use it in GitHub Desktop.
Split a command-line to an array
var splitCommand = (function(){
function State(text) {
this.args = [];
this.term = '';
this.quot = null;
this.next = null;
['split', 'quoted', 'interm', 'escape'].map(function(m){
this[m] = function(at){
at++;
if (at < text.length) {
return this['_'+m](text.charAt(at), at);
}
if (this.term != '') this.termed();
return this.args;
}.bind(this);
}.bind(this));
}
State.prototype._split = function (char, at) {
switch(char) {
case ' ':
return this.split(at);
case '"':
case "'":
this.quot = char;
return this.quoted(at);
case '\\':
this.next = this.interm;
return this.escape(at);
default:
this.term += char;
return this.interm(at);
}
};
State.prototype._quoted = function (char, at) {
switch(char) {
case this.quot:
this.termed();
return this.split(at);
case '\\':
this.next = this.quoted;
return this.escape(at);
default:
this.term += char;
return this.quoted(at);
}
};
State.prototype._interm = function (char, at) {
switch(char) {
case ' ':
this.termed();
return this.split(at);
case '\\':
this.next = this.interm;
return this.escape(at);
default:
this.term += char;
return this.interm(at);
}
};
State.prototype._escape = function (char, at) {
this.term += char;
return this.next(at);
};
State.prototype.termed = function() {
this.args.push(this.term);
this.term = '';
};
return function(text) {
return new State(text).split(-1);
}
})();
//console.log(splitCommand('hogehoge "" "\\\\" "\\" hoge" " \\" " "\\""'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment