Javascript String format(placeholders)

Description

Javascript String format(placeholders)


String.prototype.format = function (placeholders) {
    var s = this;
    for (var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }/*from  www  . ja v  a2 s .  c  om*/
    return s;
};

Javascript String format(placeholders)

// Write a function that formats a string. The function should have placeholders, as shown in the example
// Add the function to the String.prototype

String.prototype.format = function (placeholders) {
    var item,//  w  w w. j  a  va2 s.  co m
        regex,
        result = this;

    for (item in placeholders) {
        regex = new RegExp('#{' + item + '}', 'g');
        result = result.replace(regex, placeholders[item]);
    }

    return result;
};

var placeholders = {name: 'John'};
var text = 'Hello, there! Are you #{name}?';
console.log(text.format(placeholders));

var placeholders2 = {name: 'John', age: 13};
var text2 = 'My name is #{name} and I am #{age}-years-old';
console.log(text2.format(placeholders2));



PreviousNext

Related