Skip to content

Instantly share code, notes, and snippets.

@l0gicpath
Forked from atesgoral/LICENSE.txt
Created October 22, 2013 13:08
Show Gist options
  • Save l0gicpath/7100457 to your computer and use it in GitHub Desktop.
Save l0gicpath/7100457 to your computer and use it in GitHub Desktop.
function (
f // fhe format specifier
// followed by any number of arguments
) {
var a = arguments; // store outer arguments
return ("" + f) // force format specifier to String
.replace( // replace tokens in format specifier
/\{(?:(\d+)|(\w+))\}/g, // match {token} references
function (
s, // the matched string (ignored)
i, // an argument index
p // a property name
) {
return p && a[1] // if property name and first argument exist
? a[1][p] // return property from first argument
: a[i] // assume argument index and return i-th argument
})
}
function(f){var a=arguments;return(""+f).replace(/\{(?:(\d+)|(\w+))\}/g,function(s,i,p){return p&&a[1]?a[1][p]:a[i]})}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Ates Goral <http://magnetiq.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "format",
"keywords": [ "format", "string", "token", "template" ]
}
var format = function(f){var a=arguments;return(""+f).replace(/\{(?:(\d+)|(\w+))\}/g,function(s,i,p){return p&&a[1]?a[1][p]:a[i]})};
console.log(format("{1} and {2}", "apples", "pears")); // apples and pears
console.log(format("{1} {1} {2}", "hip", "hooray")); // hip hip hooray
console.log(format("{key}: {value}", { key: "life", value: 42 })); // life: 42
console.log(format("mixing {prop} and {2}", { prop: "property" }, "index"));
// mixing property and index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment