Skip to content

Instantly share code, notes, and snippets.

@rksm
Last active August 29, 2015 13:57
Show Gist options
  • Save rksm/9774371 to your computer and use it in GitHub Desktop.
Save rksm/9774371 to your computer and use it in GitHub Desktop.
Parse a JS object path
function jsPathSplitter(string) {
// STRING -> [STRING]
// ex: 'foo["bar"].x[0] -> ['foo', 'bar', x, '0']'
// for convenience even allows non-javascripty identifiers like foo.0.bar
return (function splitter(index, string, parts, term) {
if (string.length === 0) return parts;
if (index >= string.length) return parts.concat([string]);
if (string[index] === '\\') return splitter(index+2, string, parts, term); // escape char
var newTerm, skip = 0;
if (string.slice(index, index+term.length) === term) newTerm = '.' // at terminator?
else if (string[index] === '[') {
if (string[index+1] === '\'') { newTerm = '\']'; skip = 1; }
else if (string[index+1] === '"') { newTerm = '"]'; skip = 1; }
else { newTerm = ']'; skip = 0; }
}
return newTerm ?
splitter(0, string.slice(index + term.length + skip), parts.concat(index > 0 ? [string.slice(0, index)] : []), newTerm) :
splitter(index+1, string, parts, term);
})(0, string, [], '.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment