Equivalent in javascript for printf of C

4

Something that happens to me very often is to need to format a string for it I end up concatenating several chains manually, my question is if there is any implementation of printf in javascript

for those who do not know that printf

printf("Color %s, numero1 %d, numero2 %05d, hex %x, real %5.2f.\n", "rojo", 12345, 89, 255, 3.14);

would return:

Color rojo, numero1 12345, numero2 00089, hex ff, real 3.14.

Update

At the moment commented that I found a solution similar but not exact to the problem.

String.prototype.format = function() {
    var formatted = this;
    for( var idx in arguments) {
    formatted = formatted.replace(new RegExp("\{" + idx + "\}", 'g'),  arguments[idx]);
    }
    return formatted;
};

Example of use:

"hola usuario de {1}, hoy es {0}".format('viernes', 'Stack Overflow ES')
    
asked by Ricardo D. Quiroga 18.08.2017 в 17:56
source

2 answers

0

In the end I found this library sprintf that does what it needed. thank you very much anyway.

    
answered by 19.08.2017 / 06:04
source
2

Since ES6 javascript supports string interpolation something like printf in c ++

var cadena = "Adios Mundo";
console.log('${cadena}');

note that the grave accent "'" should be used instead of single or double quotes

    
answered by 18.08.2017 в 21:43