Skip to content

Instantly share code, notes, and snippets.

@hejrobin
Created August 3, 2011 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hejrobin/1122124 to your computer and use it in GitHub Desktop.
Save hejrobin/1122124 to your computer and use it in GitHub Desktop.
// I moustache you a question, but I'll shave it for later...
String.prototype.moustache = function(object, regex) {
return this.replace(regex || (/\\?\{\{([^{}]+)\}\}/g), function(match, key) {
if(match.charAt(0) == '\\')
return match.slice(1);
return (object[key] !== null) ? object[key] : '';
});
};
// Simple usage
var simple = "It's all about {{apples}} and {{oranges}}!".moustache({
'apples': 'bananas',
'oranges': 'kiwis'
});
// Custom regex[p]
var custom = "No %name%, these men are nihilists...".moustache({
'name': 'Donnie'
}, /\\?\%([^{}]+)\%/g);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment