Skip to content

Instantly share code, notes, and snippets.

@aloha1003
Created August 22, 2016 09:22
Show Gist options
  • Save aloha1003/9aae6809c96d5929b82a38e71c4f7cff to your computer and use it in GitHub Desktop.
Save aloha1003/9aae6809c96d5929b82a38e71c4f7cff to your computer and use it in GitHub Desktop.
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
var compareStr = '';
var map = {};
if ( (arguments.length == 1) && (typeof arguments[0] === 'object')) {
for (var prop in arguments[0]) {
key = prop;
compareStr += key+'|';
map['{'+key+'}'] = arguments[0][prop];
}
} else {
while (i--) {
key = i;
compareStr += key+'|';
map['{'+key+'}'] = arguments[i];
}
}
var regExp = new RegExp("{("+compareStr+")}", "g");
s = s.replace(regExp, function (matched){
return map[matched];
});
return s;
};
var test = "Hello {name}, {world}";
var test2 =" Hello {0}, {1}";
console.log(test.format({"name":"A", "world" : "B"}));
console.log(test2.format("C","D"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment