Skip to content

Instantly share code, notes, and snippets.

@cyrillsemenov
Created April 11, 2024 14:49
Show Gist options
  • Save cyrillsemenov/c667adc8cb828260b54396ef3daa7b94 to your computer and use it in GitHub Desktop.
Save cyrillsemenov/c667adc8cb828260b54396ef3daa7b94 to your computer and use it in GitHub Desktop.
Format JS
String.prototype.format = String.prototype.format ||
function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
// Replace: ([\w\.]+).format\(
// To: formatText($1,
function formatText (template, data) {
var template = template.toString();
for (key in data) {
template = template.replace(new RegExp("\\{" + key + "\\}", "gi"), data[key]);
}
return template;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment