Use string.format in javascript

This is a pretty neat snippet that attaches a format function to the string object. Works with infinit number of arguments: mystring.format('{0} and {1} and {2} and etc..', 'one', 'two', 'three');
<script type="text/javascript">
      
String.prototype.format = function() {
var formatted = this;
for (i=0;i<arguments.length;i++) {
formatted = formatted.replace("{" + i + "}", arguments[i]);
}
return formatted;
};

alert('{0} is {1}!'.format('this','awesome'));
</script>

Code provided by my college Axtelius.

Related posts:

Comments

comments powered by Disqus