¿Cómo interpolar variables en cadenas en JavaScript, sin concatenación?


Sé que en PHP podemos hacer algo como esto:

$hello = "foo";
$my_string = "I pity the $hello";

Salida: "I pity the foo"

Me preguntaba si esto mismo es posible en JavaScript. Usar variables dentro de cadenas sin usar concatenación-se ve más conciso y elegante para escribir.

Author: Xufox, 2010-07-22

10 answers

A partir de Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, puede usar una función ES2015 / ES6 llamada Literales de plantilla y usar esta sintaxis:

`String text ${expression}`

Los literales de plantilla están encerrados por la marca de retroceso (` `) (acento grave) en lugar de comillas dobles o simples.

Ejemplo:

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.

¿Qué tan limpio es eso?

Bono:

También permite cadenas multilíneas en javascript sin escapar, lo cual es genial para plantillas:

return `
    <div class="${foo}">
         ...
    </div>
`;

Soporte del navegador:

Como esta sintaxis no es compatible con los navegadores más antiguos (Internet Explorer y Safari Babel para transpilar su código en ES5 para asegurarse de que se ejecutará en todas partes.


nota al margen:

A partir de IE8 + puede usar el formato de cadena básico dentro de console.log:

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
 375
Author: bformet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-14 19:22:18

Antes de Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no, eso no era posible en javascript. Usted tendría que recurrir a:

var hello = "foo";
var my_string = "I pity the " + hello;
 151
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:45

Antes de Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Aunque podrías probar sprintf para JavaScript para llegar a mitad de camino:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
 37
Author: Justin Ethier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:56

Bueno, podrías hacer esto, pero no es esp general

'I pity the $fool'.replace('$fool', 'fool')

Podría escribir fácilmente una función que haga esto de manera inteligente si realmente necesita

 25
Author: Scott Evernden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-21 21:34:23

Si te gusta escribir CoffeeScript puedes hacer:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript en realidad ES javascript, pero con una sintaxis mucho mejor.

Para obtener una visión general de CoffeeScript, consulte esta guía para principiantes.

 8
Author: bformet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-13 10:38:59

Respuesta completa, lista para ser utilizada:

 var Strings = {
        create : (function() {
                var regexp = /{([^{]+)}/g;

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};

Llamar como

Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});

Para adjuntarlo a String.prototipo:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}

Luego use como:

"My firstname is ${first}".create({first:'Neo'});
 8
Author: momo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-05 17:25:28

Puede usar esta función javascript para hacer este tipo de plantillas. No es necesario incluir una biblioteca completa.

function createStringFromTemplate(template, variables) {
    return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
        return variables[varName];
    });
}

createStringFromTemplate(
    "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
    {
        list_name : "this store",
        var1      : "FOO",
        var2      : "BAR",
        var3      : "BAZ"
    }
);

Producto: "I would like to receive email updates from this store FOO BAR BAZ."

Usando una función como argumento para la cadena.la función replace () era parte de la especificación ECMAScript v3. Vea esto para responder para más detalles.

 7
Author: Eric Seastrand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-05 19:09:16

Si estás tratando de hacer interpolación para microtemplar, me gusta Bigote.js con ese fin.

 4
Author: Joe Martinez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-21 21:32:48

Escribí este paquete npm stringinject https://www.npmjs.com/package/stringinject que le permite hacer lo siguiente

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

Que reemplazará los {0} y {1} con los elementos de la matriz y devolverá la siguiente cadena

"this is a test string for stringInject"

O puede reemplazar los marcadores de posición con claves de objeto y valores como estos:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 
 2
Author: tjcafferkey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 16:20:40

No veo ninguna biblioteca externa mencionada aquí, pero Lodash tiene _.template(),

Https://lodash.com/docs/4.17.10#template

Si ya está haciendo uso de la biblioteca, vale la pena echarle un vistazo, y si no está haciendo uso de Lodash, siempre puede seleccionar métodos de npm npm install lodash.template para que pueda reducir los gastos generales.

Forma más simple -

var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'

También hay un montón de opciones de configuración -

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'

Encontré delimitadores personalizados más Interesante....

 1
Author: Mark Carpenter Jr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 19:14:27