String Replacement is Natively Supported by console.log()

I recently found out that console.log() in JavaScript natively supports string replacement using %s as a placeholder and I wanted to share.

console.log('My name is %s.', 'Alex');  
// My name is Alex.

In addition you can use %s as many times as you have arguments and it will replace them in order.

console.log('My first name is %s and my last name is %s.', 'Alex', 'Ford');  
// My first name is Alex and my last name is Ford.

Native string replacement also works in console.warn() and console.error().

This is similar to string.Format() in C# except you don't have to specify an index in the placeholder such as string.Format("My name is {0} {1}.", "Alex", "Ford");. Unfortunately, not specifying an index means that you can only use each argument one time because after it replaces one placeholder with one argument it replaces the next placeholder with the next argument.

console.log('My name is %s %s', 'Alex');  
// My name is Alex %s

If you really want functionality similar to C#'s string.Format() just paste this simple function into your application.

String.format = function (str) {  
    var args = arguments;
    return str.replace(/\{([0-9]+)\}/g, function (match, index) {
        return args[parseInt(index) + 1];
    });
};

With that you can now use placeholders that specify an index.

var str = "The sky is {1} and water is {1}, but my favorite color is {0}.";  
console.log(String.format(str, 'green', 'blue'));  
// The sky is blue and water is blue, but my favorite color is green.

If you really want to get fancy then you can add that method to the string prototype.

String.prototype.format = function () {  
    var args = arguments;
    return this.replace(/\{([0-9]+)\}/g, function (match, index) {
        return args[parseInt(index)];
    });
};

Now you can call format on the string instance itself.

var str = "The sky is {1} and water is {1}, but my favorite color is {0}.";  
console.log(str.format('green', 'blue'));  
// The sky is blue and water is blue, but my favorite color is green.

Chev

Read more posts by this author.

comments powered by Disqus