Skip to content

Instantly share code, notes, and snippets.

@sbstp
Created May 29, 2014 17:24
Show Gist options
  • Save sbstp/3c6ff36a6d1da7970a83 to your computer and use it in GitHub Desktop.
Save sbstp/3c6ff36a6d1da7970a83 to your computer and use it in GitHub Desktop.
function split(string) {
var curr
, lastQuoteIndex = 0
, lastSpaceIndex = 0
, parts = []
, isInQuotes = false;
for (var i = 0; i < string.length; i++) {
curr = string[i];
if (curr === '"') {
if (isInQuotes) {
parts.push(string.substring(lastQuoteIndex + 1, i));
isInQuotes = false;
lastSpaceIndex = -1;
} else {
isInQuotes = true;
lastQuoteIndex = i;
}
}
if (/^\s$/.test(curr)) {
if (!isInQuotes) {
if (lastSpaceIndex === -1) {
lastSpaceIndex = i;
} else {
parts.push(string.substring(lastSpaceIndex + 1, i));
lastSpaceIndex = i;
}
}
}
}
return parts;
}
console.log(split('"fish" boo biz "bar bax" qrt "zoo"'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment