Time for a quick inspirational solution to have something similar in JavaScript as string.Format("Hello {0} {1}!", "Daniel", "Wertheim"); in C#.

String.prototype.apply = String.prototype.apply || function () {
    var arg,
        v = this.valueOf();

    if (!v)

    for (var i = 0, m = arguments.length; i < m; i++) {
        arg = arguments[i];
        if (arg === undefined)
            arg = null;

        regExp = new RegExp('\\{' + i + '\\}', 'gm');
        v = v.replace(regExp, arg);

    return v;

This can now easily be used like this:

'Hello {0} {1}!'.apply("Daniel", "Wertheim");

Works for me, hope it’s to any help. Please feel free to suggest improvements.


Development, JavaScript

Join the conversation! 3 Comments

  1. […] One way to get string.Format support in JavaScript – Daniel Wertheim […]

  2. Why don’t you call the function ‘format’ instead of ‘apply’ for an even more similar solution?

    • Because I have a similar extension method in c# and want the namings to be the same and I don’t really like how format reads when it’s called “on” the format. Then it should be something like formatWith, which might also read better than apply :-)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 33 other followers

%d bloggers like this: