stringFormat

by John Allan

HTML

<div id="content"></div>
<div id="JSONcontent"></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}}", {
    "first": "rock",
    "second": "roll"
}));