danielwertheim

danielwertheim


notes from a passionate developer

Developer that lives by the mantra "code is meant to be shared".

Share


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

One way to get string.Format support in JavaScript

Daniel WertheimDaniel Wertheim

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,
        regExp,
        v = this.valueOf();

    if (!v)
        return;

    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.

//Daniel

Developer that lives by the mantra "code is meant to be shared".

Comments