Skip to content

Instantly share code, notes, and snippets.

@NuckChorris
Last active September 27, 2015 05:18
Show Gist options
  • Select an option

  • Save NuckChorris/1218052 to your computer and use it in GitHub Desktop.

Select an option

Save NuckChorris/1218052 to your computer and use it in GitHub Desktop.
module.exports = function Parse (template, obj) {
if (arguments.length === 1) {
return template;
} else if (arguments.length === 2) {
if (arguments[1] == null) {
return template;
} else if (typeof arguments[1] === 'object') {
var obj = arguments[1];
} else if (typeof arguments[1] === 'Array') {
var obj = arguments[1];
} else {
var obj = [arguments[1]];
}
} else if (arguments.length > 1) {
var obj = Array.slice.call(arguments, 1);
} else {
return template;
}
return template.replace(/\{([a-zA-Z\.0-9]*)\}/mg, function (match, key) {
var parts = key.split('.');
for (var i = 0, l = parts.length; i < l; ++i) {
if (!obj[parts[i]] || obj[parts[i]] === null) return match;
obj = obj[parts[i]];
}
return obj;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment