Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a sprintf equivalent in JavaScript?

Tags:

javascript

If so, what is it?

I don't mind if it involves using an external library.

like image 583
Dawid Ohia Avatar asked Jun 24 '26 22:06

Dawid Ohia


1 Answers

Here my super simple solution which can handle %s, %d and %04d (change 4 on any number)

function sprintf(str) {
    var args = arguments, i = 1;

    return str.replace(/%(s|d|0\d+d)/g, function (x, type) {
        var value = args[i++];
        switch (type) {
        case 's': return value;
        case 'd': return parseInt(value, 10);
        default:
            value = String(parseInt(value, 10));
            var n = Number(type.slice(1, -1));
            return '0'.repeat(n).slice(value.length) + value;
        }
    });
}
like image 163
redexp Avatar answered Jun 27 '26 13:06

redexp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!