How to make formatting strings easier

The String.format() function is a small function that RGraph adds to the built-in JavaScript String object. It's similar in operation to the widely understood sprintf() function in that it allows you to add placeholders into your string which are then replaced by the arguments that you give to the function.

This makes building strings much easier and more easily understood when it comes to rereading the code back at a later date. In particular it makes building and reading SVG paths much easier.

The function originally came from an answer on StackOverflow.

Here's the function as it is in the SVG core file:

//
// A function to make the formatting of strings easier to
// handle and more readable. Usage:
//
// var str = '{1} sat on the {2}'.format(
//     'The cat',
//     'mat'
// );
//
String.prototype.format = function()
{
    var args = arguments;

    return this.replace(/{(\d+)}/g, function(str, idx)
    {
      return typeof args[idx - 1] !== 'undefined' ? args[idx - 1] : str;
    });
};

As you can see there's not a great deal to the function - just a regular expression that uses a function to handle the replacement.

The function uses the format: {1} as the place holder in your string but you could change this to something else if you wanted to like this:

//
// A function to make the formatting of strings easier to
// handle and more readable. Usage:
//
// var str = '%1 sat on the %2'.format(
//     'The cat',
//     'mat'
// );
//
String.prototype.format = function()
{
    var args = arguments;

    return this.replace(/%(\d+)/g, function(str, idx)
    {
      return typeof args[idx - 1] !== 'undefined' ? args[idx - 1] : str;
    });
};

How to use the function

As shown in the comments above the function, after you have added it to your code you can use it like this:

var str = '{1} sat on the {2}'.format(
    'The cat',
    'mat'
);

Which is (in my opinion) eminently more readable than inline concatention like this:

var var1 = 'The cat',
    var2 = 'mat',
    str  = var1 + ' sat on the ' + var2

Which only gets less readable the bigger your string and the more substitutions that you do.

Another thing that you can do with this function is multiple replacements reusing arguments. So you can have {1} and {2} replacements multiple times in your string like this:

 var str = '{1} sat on the {2}. {1} really did sit on the {2}!'.format(
     'The cat',
     'mat'
 );