Skip to content

Instantly share code, notes, and snippets.

@osiyuk
Forked from jonathanconway/string.prototype.format.js
Last active November 24, 2016 23:49
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 osiyuk/d18ec38ceae0e12f7a6ed7be9077b6f7 to your computer and use it in GitHub Desktop.
Save osiyuk/d18ec38ceae0e12f7a6ed7be9077b6f7 to your computer and use it in GitHub Desktop.
Straight-forward string.prototype format method for Javascript.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
// it`s monkey patching, breaks incapsulation and considered bad practice
String.prototype.format = function() {
var s = this;
for (var i = 0; i < arguments.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i]);
}
return s;
}
// better to invert loop
// https://regex101.com/r/u4HkIt/1
String.prototype.format = function() {
var reg = new RegExp('{\s*[^}]*\s*}', 'g'),
found = this.match(reg),
object = typeof arguments[0] === 'object',
s = this,
sub, key;
if (object) object = arguments[0];
if (object) while (found.length) {
sub = found.shift();
key = sub.slice(1, -1).trim();
if (key in object)
s = s.replace(sub, object[key]);
}
else while (found.length) {
sub = found.shift();
key = parseInt(sub.slice(1, -1));
s = s.replace(sub, arguments[key]);
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment