Skip to content

Instantly share code, notes, and snippets.

@timruffles
Created December 15, 2015 12:01
Show Gist options
  • Save timruffles/40a3d48796b9cf7aceb9 to your computer and use it in GitHub Desktop.
Save timruffles/40a3d48796b9cf7aceb9 to your computer and use it in GitHub Desktop.
reads strings like `" 'hello I am string one', \"i'm string two\" 'cool ' "` into `["hello I am string one", "i'm string two", "cool "]`
// read a list of strings which are enclosed in quotes. ignores whitespace (= anything outside quotes)
function readQuoted(s) {
var i = 0;
var quote = false;
var strs = [];
var str = "";
var c;
while(c = s[i++]) {
if(quote) {
if(c === quote) {
quote = false;
strs.push(str);
str = "";
} else {
str += c;
}
} else if(c === "'" || c === '"') {
quote = c;
}
}
if(quote) {
throw new Error("unclosed quote <" + quote + "> in <" + s.slice(0, i) + ">");
}
return strs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment