Last active
August 29, 2015 14:13
-
-
Save kyoh86/055285d960259cb4b2de to your computer and use it in GitHub Desktop.
Split a command-line to an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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