Created
April 11, 2024 14:49
-
-
Save cyrillsemenov/c667adc8cb828260b54396ef3daa7b94 to your computer and use it in GitHub Desktop.
Format JS
This file contains hidden or 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
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