String format and replace
String format and replace
by Nirvanachain
JavaScript
/**
* do string formatting
* stringFormat('{0} {1}', 'foo', '2') === 'foo 2'
*/
function stringFormat(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return (typeof args[number] !== 'undefined') ? args[number] : match;
})
}
console.log( stringFormat('hi {0}, how is {1} and {2}?', 'bob', 'mary', 'paul') );