stringFormat
HTML
<div id="content"></div>
<div id="JSONcontent"></div>
<div id="stringFormatContent"></div>
CSS
div{
padding:20px 0
}
JavaScript
var stringFormat = function (str, arr) {
a = (typeof arguments[1] === 'object') ? arr : Array.prototype.slice.call(arguments).slice(1);
return str.replace(
/\{([0-9]+)\}/g,
function (_, index) { return a[index]; });
};
$("#content").text(stringFormat("{0} and or {1} {1}", "rock", "roll"));
var JSONStringFormat = function (s, o) {
var k;
for (k in o) {
if (o.hasOwnProperty(k)) {
s = s.replace("{" + k + "}", o[k]);
}
}
return s;
};
$("#JSONcontent").text(JSONStringFormat("{first} and or {second} {second}", {
"first": "rock",
"second": "roll"
}));
String.prototype.format=function(){
return(
function (a, t) {
//(?<=\[)(.*?)(?=\])
return t.replace(/\{(?=\{)(\d+)\}(?=\})/g, '{$1}')
.replace(/\{(\d+)\}/g,
function (_, i) {
return a[~~i];
});
})(arguments, this);
};
$("#stringFormatContent").text("{0} {0}, {0} {1} {{2}}".format("rock", "role", "high school"));