Inline string formatting with Javascript

One thing I miss in javascript coming from Ruby and Python is a quick and easy way to format strings.

It’s quite common in javascript to see developers doing things like

var str = 'my name is ' + name;

Which I find messy and unintuative.

Therefore, here’s something I use in my node apps to make string formatting a bit easier

var format = require('util').format;

 * Formats a string by replacing the placeholds with
 * with the specified variables 
String.prototype.fmt = function(){
	var str = this.valueOf();
    var args = [str].concat([];
    return format.apply(null, args);

Then to use it

console.log("my name is %s, it's a nice day.".fmt('Michael'));
>> my name is Michael, it's a nice day.

Much better.

You’ll notice a few interesting things about this code, for one, I’m using the valueOf this. This is because otherwise this is a String object instead of a string primitive and format expects a primitive.

If you’re new to javascript you might not be familiar with the call and apply methods. In the case of [] we’re calling the Array.slice function, passing arguments as this. This basically converts the arguments object into an array.

The other neat trick is the use of apply. The format method has a signature of format(input: string, args…), so it expects a single string as the first input then an unknown number of arguments. To get the inputs in the order format expects we use concat to make an array that looks like [inputString, args…] then apply calls format while expanding the input array into format(inputString, arg1, arg2…).

Now of course this function only works inside node since that’s the only place you’ll find util, however I have a regex based solution I use within the browser, which I’ll share once I clean it up.