Created
February 21, 2014 13:34
-
-
Save ttldtor/9134293 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!String.prototype.format) { | |
String.prototype.format = function() { | |
var me = this; | |
function replacer4Array(a) { | |
return me.replace(/{(\d+)}/g, function(match, number) { | |
var n = parseInt(number, 10); | |
if (isNaN(n) || typeof a[n - 1] === "undefined") { | |
return match; | |
} else { | |
return a[n - 1]; | |
} | |
}); | |
} | |
function replacer4Object(o) { | |
return me.replace(/{(\S+?)}/g, function(match, name) { | |
return typeof o[name] !== "undefined" ? o[name] : match; | |
}); | |
} | |
var args = arguments; | |
switch (args.length) { | |
case 0: break; | |
case 1: | |
var a = args[0]; | |
if (a instanceof Object) { | |
if (a instanceof Array) { | |
return replacer4Array(a); | |
} else { | |
return replacer4Object(a); | |
} | |
} else { | |
return replacer4Array([a]); | |
} | |
break; | |
default: | |
return replacer4Array(args); | |
} | |
return this; | |
} | |
} | |
/* Example | |
console.log("{1}{2}{1}".format([111, 222])); | |
console.log("{abc}{dfg}{abc}".format({abc: 123, dfg: 345})); | |
console.log("{1}{2}{1}".format(111, 222)); | |
console.log("{1}{2}{1}".format(111)); | |
console.log("{1}{2}{1}".format("111")); | |
console.log("{abc}{dfg}{abc}".format({abc: 123})); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment