Last Updated: February 25, 2016
·
420
· vampireneo

string.format for javascript

Code:

String.prototype.format = function() {
  var str = this;
  for (var i = 0; i <= arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    str = str.replace(reg, arguments[i]);
  }
  return str;
};

Usage:

console.log("Hello, {0}, today is {1}!".format("Tom", "Monday"));

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside