Skip to content

Instantly share code, notes, and snippets.

@insin
Created March 1, 2014 23:51
Show Gist options
  • Save insin/9299542 to your computer and use it in GitHub Desktop.
Save insin/9299542 to your computer and use it in GitHub Desktop.
/**
* Replaces string {placeholders} with properties of a given object, but
* interpolates into and returns an array instead of a string.
* By default, any resulting empty strings are stripped out of the array. To
* disable this, pass an options object with a 'strip' property which is false.
*/
function formatToArray(str, obj, options) {
var parts = str.split(/\{(\w+)\}/g)
for (var i = 1, l = parts.length; i < l; i += 2) {
parts[i] = (object.hasOwn(obj, parts[i])
? obj[parts[i]]
: '{' + parts[i] + '}')
}
if (!options || (options && options.strip !== false)) {
parts = parts.filter(function(p) { return p !== ''})
}
return parts
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment