Skip to content

Instantly share code, notes, and snippets.

@rickmark
Created February 18, 2010 17:38
Show Gist options
  • Save rickmark/307876 to your computer and use it in GitHub Desktop.
Save rickmark/307876 to your computer and use it in GitHub Desktop.
Initial parse command for Narwhal
function parseArguments(arguments)
{
var startsWith = function(self, str) { return (self.match("^"+str.replace('\\', '\\\\'))==str) }
var endsWith = function(self, str) { return (self.match(str.replace('\\', '\\\\')+"$")==str) }
var results = [], quoteType = null, quotedElement = null;
arguments.split(' ').forEach(function(element) {
if (quoteType || endsWith(element, '\\') || startsWith(element, '\'') || startsWith(element, '"')) {
if (quoteType) {
if (endsWith(element, quoteType)) {
results.push(quotedElement + " " + element.substring(0, element.length - 1));
quotedElement = null;
quoteType = null;
return;
}
else { quotedElement += " " + element; return; }
}
if (!quoteType && startsWith(element, '\'')) {
quoteType = '\'';
quotedElement = element.substring(1, element.length);
return;
}
if (!quoteType && startsWith(element, '"')) {
quoteType = '"';
quotedElement = element.substring(1, element.length);
return;
}
if (!quoteType) {
if (endsWith(element, '\\')) {
if (quotedElement) { quotedElement += " " + element; }
else { quotedElement = element; }
}
else { results.push(quotedElement + ' ' + element); quotedElement = null; return; }
}
}
else {
if (quotedElement) { results.push(quotedElement+' '+element); quotedElement = null;}
else { results.push(element); }
}
});
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment