Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Forked from 140bytes/LICENSE.txt
Created May 21, 2011 08:48
Show Gist options
  • Save atesgoral/984375 to your computer and use it in GitHub Desktop.
Save atesgoral/984375 to your computer and use it in GitHub Desktop.
Variable-argument string formatter with {token} syntax that supports object properties and argument indices
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
@maettig
Copy link

maettig commented Nov 11, 2011

You can save 6 bytes if you like. Omit one of the three parentheses. Omit the backslash escaping (because { is not followed by a number).

function(f){var a=arguments;return(""+f).replace(/{(\d+|(\w+))}/g,function(s,i,p){return p&&a[1]?a[1][p]:a[i]})}

Also see @tkissing's mustacheStyleTemplatesCompressed that does similar string formatting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment