Skip to content

Instantly share code, notes, and snippets.

@panzi
Created September 14, 2013 03:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panzi/6558645 to your computer and use it in GitHub Desktop.
Save panzi/6558645 to your computer and use it in GitHub Desktop.
Very simple string interpolation in JavaScript. {} expands to positional arguments, {NAME} to named arguments, {{ to {, and }} to }.
function format (fmt, kwargs) {
var args = arguments;
var index = 1;
return fmt.replace(/{([^{}]*)}|{{|}}|{|}/g, function (match, key) {
if (key !== undefined) {
if (key) {
return kwargs[key];
}
else {
return args[index ++];
}
}
switch (match) {
case '{{': return '{';
case '}}': return '}';
case '{': throw new SyntaxError('Unmatched left curly bracket "{" in format.');
case '}': throw new SyntaxError('Unmatched right curly bracket "}" in format.');
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment