Skip to content

Instantly share code, notes, and snippets.

@ninetails
Forked from flesch/sprintf.as
Last active August 29, 2015 14:09
Show Gist options
  • Save ninetails/ab2a256ee4af12ffccc2 to your computer and use it in GitHub Desktop.
Save ninetails/ab2a256ee4af12ffccc2 to your computer and use it in GitHub Desktop.
function sprintf(){
var args = Array.prototype.slice.call(arguments), f:Array = [], str = args.shift().split("%s");
while (str.length) {
f.push(str.shift(), args.shift() || "");
}
return f.join("");
}
trace(sprintf("Hello %s, how ya %s?", "motherf*cker", "durin"));
function sprintf(){
var args = Array.prototype.slice.call(arguments);
return args.shift().replace(/%s/g, function(){
return args.shift();
});
}
alert(sprintf("Hello %s, how ya %s?", "motherf*cker", "durin"));
// http://mir.aculo.us/2011/03/09/little-helpers-a-tweet-sized-javascript-templating-engine/
function t(s,d){
for(var p in d)
s = s.replace(new RegExp('{'+p+'}','g'), d[p]);
return s;
}
// t("Hello {who}!", { who: "JavaScript" }); -> "Hello JavaScript!"
function x(s, d) {
return s.replace(/\{([\w]+)\}/ig, function(a, b){
return d[b];
});
}
// x("Hello {who}!", { who: "JavaScript" }); -> "Hello JavaScript!"
// http://jsperf.com/tweet-sized-template-engines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment