Quite often I need to create a formatted string with padded numbers or other replacement text so to reproduce a useful function like that which is available in C or C++ (and other languages) I decided to create a simple method on the String class to recreate the following function signature:
var message = String.format('Hello %s, the time is %02d:%02d!', name, hour, minute );Options:
%s : replace with a string %5s : replace with a string padded with spaces to 5 characters in length %d : replace with an integer, throws if not a number %03d : replace with an integer padded with zeroes to 3 significant figures %4d : replace with integer padded with spaces to4 significant figures %x : replace with an integer converted to hex, throws if not a number %X : replace with an integer converted to upper case hex, throws if not a number %03x : replace with an integer converted to hex padded with zeroes to 3 characters in length %4x : replace with an integer converted to hex padded with spaces to 4 characters in length
Here is the code, as you can see it uses a useful array method “reduce” which calls the callback function on each element of the array to produce our results:
String.format = function() {
var formatArguments = [].slice.call( arguments );
var formatDefinition = formatArguments.shift();
function replacer( text, replacement ) {
var pad = function(value, size, padValue) {
var s = value+"";
while (s.length < size) s = padValue + s;
return s;
};
var type = new RegExp( "%([0-9]*)(d|x|X|s)" );
var matches = type.exec( text );
console.log ( matches );
var replacementValue = replacement;
if( matches && matches.length >= 1 )
{
if( matches[2] === "s" )
{
replacementValue = pad( replacement, matches[1], " " );
}
else if( matches.length > 2 && (matches[2] === "d" || matches[2].toLowerCase() === "x") )
{
if( typeof(replacement) !== "number" )
throw new Error( "Parameter " + formatArguments.length + " '" + replacement + "' is not a number" );
replacementValue = matches[2] === "x" ? replacement.toString(16) : (matches[2] === "X" ? replacement.toString(16).toUpperCase() : replacement);
replacementValue = pad( replacementValue, matches[1], matches[1].length > 0 && matches[1][0] === "0" ? "0" : " " );
}
text = text.replace(matches[0], replacementValue );
}
return text.replace( /%%/, "%" );
}
return formatArguments.reduce( replacer, formatDefinition );
};
// Some testing
var name = 'Dan';
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var message = String.format("Hello '%5s', the time is %s:%s - is %d:%012d - a hex value %x or upper hex %06X as a percentage %d%% as %% are escaped", name, hour, minute, hour, minute, 95, 95, 23 );
console.log(message);Would result in the following output:
Hello ' Dan', the time is 11:48 - is 11:000000000048 - a hex value 5f or upper hex 00005F as a percentage 23% as % are escaped