HOWTO: 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 that 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.com.
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:
//
// 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:
//
// 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:
str = '{1} sat on the {2}'.format( 'The cat', 'mat' );
Which is (in my opinion) eminently more readable than inline concatenation like this:
var1 = 'The cat'; var2 = 'mat'; str = var1 + ' sat on the ' + var2
Which only gets less readable the bigger your string is 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:
str = '{1} sat on the {2}. {1} really did sit on the {2}!'.format( 'The cat', 'mat' );
January 2021 update
Now, from the version 5.27 release, you can also use named placeholders that refer directly to (by default) global variables. This can make your code more readable in some cases. It would change the above example code to look like this:
// // An example of named arguments. // what = 'cat'; // A global variable where = 'mat'; // A global variable str = 'The {what} sat on the {where}'.format();