Esta tradução está incompleta. Ajude atraduzir este artigo.
This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.
Resumo
Template strings são literais string permitindo expressões embutidas. Você pode usar string multi-linhas e interpolação de string com elas.
Síntaxe
`corpo de texto`
`texto linha 1
texto linha 2`
`texto string ${expression} texto string`
tag `texto string ${expression} texto string`
Descrição
Template strings são envolvidas por crases (` `) em vez de aspas simples ou duplas. Template strings podem possuir espaços reservados. Existem indicadores pelo sinal de Dólar e aspas (${expression}). As expressões nos espaços reservados e o texto contido nelas são passados à uma função. A função padrão apenas concatena as partes em uma string única. Se existir uma expressão precedendo a template string (tag aqui), a template string é definida como "tagged template string". No caso, a expressão tag (geralmente uma função) é chamada pela template string processada, que você pode manipular antes de produzir o resultado.
Strings multi-linhas
Qualquer caracter de nova linha inserido no código é parte da template string. Utilizando strings normais, você teria de usar a síntaxe a seguir para obter strings multi-linhas:
console.log("texto string linha 1\n\
texto string linha 2");
// "texto string linha 1"
// "texto string linha 2"
Para obter o mesmo efeito com strings multi-linhas, você agora pode escrever:
console.log(`texto string linha 1 texto string linha 2`); // "texto string linha 1 // texto string linha 2"
Interpolação de Expressões
Para encapsular expressões dentro de strings, você precisava utilzar a seguinte síntaxe:
var a = 5;
var b = 10;
console.log("Quinze é " + (a + b) + " e não " + (2 * a + b) + ".");
// "Quinze é 15 e não 20."
Agora, com template strings, você pode utilizar as substituções sintaticas tornando o código mais legível:
var a = 5;
var b = 10;
console.log(`Quinze é ${a + b} e não ${2 * a + b}.`);
// "Quinze é 15 e não 20."
Tagged template strings
A more advanced form of template strings are tagged template strings. With them you are able to modify the output of template strings using a function. The first argument contains an array of string literals ("Hello " and " world" in this example). The second, and each argument after the first one, are the values of the processed (or sometimes called cooked) substitution expressions ("15" and "50" here). In the end, your function returns your manipulated string.
var a = 5;
var b = 10;
function tag(strings, ...values) {
console.log(strings[0]); // "Hello "
console.log(strings[1]); // " world"
console.log(values[0]); // 15
console.log(values[1]); // 50
return "Bazinga!";
}
tag`Hello ${ a + b } world ${ a * b}`;
// "Bazinga!"
Raw strings
The special raw property, available on the first function argument of tagged template strings, allows you to access the raw strings as they were entered.
function tag(strings, ...values) {
return strings.raw[0];
}
tag`string text line 1 \n string text line 2`;
// "string text line 1 \\n string text line 2"
In addition, the String.raw() method exists to create raw strings just like the default template function and string concatenation would create.
String.raw`Hi\n${2+3}!`; // "Hi\\n5!"
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 6 (ECMA-262) The definition of 'Template Literals' in that specification. ECMAScript 6 (ECMA-262) The definition of 'Tagged Templates' in that specification. |
Release Candidate | Initial definition. |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | Não suportado | 34 (34) | Não suportado | Não suportado | Não suportado |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | Não suportado | Não suportado | 34.0 (34) | Não suportado | Não suportado | Não suportado |