Skip to content

Instantly share code, notes, and snippets.

@anhulife
Created July 22, 2014 08:20
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 anhulife/d01feaba2ff3239f26da to your computer and use it in GitHub Desktop.
Save anhulife/d01feaba2ff3239f26da to your computer and use it in GitHub Desktop.
//format('hello {0}!', 'world') => 'hello world!'
//format('hello {0}!{1}', 'world', 'OK') => 'hello world!OK'
//format('hello {0}!', ['world']) => 'hello world!'
//format('hello {0}!{1}', ['world', 'OK']) => 'hello world!'
function format(str){
var dataList = (/array/i).test(Object.prototype.toString.apply(arguments[1])) ? arguments[1] : Array.prototype.slice.apply(arguments, [1]);
return str.replace(/\{(\d+)\}/g, function(target, index){
index = parseInt(index, 10);
return dataList[index] || '';
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment