1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
|
---
title: Stringhe template
slug: Web/JavaScript/Reference/template_strings
translation_of: Web/JavaScript/Reference/Template_literals
---
<div>{{JsSidebar("More")}}</div>
<p>Le stringhe template sono stringhe letterali che consentono espressioni incorporate. Puoi usare stringhe multi-linea e caratteristiche di interpolazione stringa con esse.</p>
<h2 id="Sintassi">Sintassi</h2>
<pre class="syntaxbox">`stringa testo`
`stringa testo linea 1
stringa testo linea 2`
`stringa testo ${espressione} stringa testo`
tag `stringa testo ${espressione} stringa testo`
</pre>
<h2 id="Descrizione">Descrizione</h2>
<p>Le stringhe template sono racchiuse dal carattere backtick (` `) (<a href="https://it.wikipedia.org/wiki/Accento_grave">accento grave</a>) invece delle singole o doppie virgolette. Le stringhe template possono contenere segnaposti. Questi sono indicati dal segno del Dollaro e parentesi graffe (<code>${espressione}</code>). Le espressioni nei segnaposti e nel testo compreso vengono passati ad una funzione. La funzione predefinita semplicemente concatena le parti in una stringa. Se c'è un'espressione che precede (<code>tag</code> qui), la stringa template è chiamata "stringa template taggata". In questo caso, l'espressione tag (di solito una funzione) viene chiamata con la stringa template processata, con cui puoi in seguito manipolare prima dell'output.</p>
<h3 id="Stringhe_multilinea">Stringhe multilinea</h3>
<p>Ogni carattere di nuova linea inseriti nel sorgente sono parte della stringa template. Usando stringhe normali, potresti usare la seguente sintassi per ottenere stringhe multilinea:</p>
<pre class="brush: js">console.log("stringa testo linea 1\n"+
"stringa testo linea 2");
// "stringa testo linea 1
// stringa testo linea 2"</pre>
<p>Per avere lo stesso effetto con le stringhe multilinea, puoi adesso scrivere:</p>
<pre class="brush: js">console.log(`stringa testo linea 1
stringa testo linea 2`);
// "stringa testo linea 1
// stringa testo linea 2"</pre>
<h3 id="Interpolazione_di_espressioni">Interpolazione di espressioni</h3>
<p>Per incorporare espressioni dentro normale stringhe, potresti fare uso della seguente sintassi:</p>
<pre class="brush: js">var a = 5;
var b = 10;
console.log("Quindici è " + (a + b) + " e\nnon " + (2 * a + b) + ".");
// "Quindici è 15 e
// non 20."</pre>
<p>Adesso, con le stringhe template, puoi fare uso della sintassi ridotta facendo sostituzioni come questa più leggibile:</p>
<pre class="brush: js">var a = 5;
var b = 10;
console.log(`Quindici è ${a + b} e\nnon ${2 * a + b}.`);
// "Quindici è 15 e
// non 20."</pre>
<h3 id="Stringhe_template_taggate">Stringhe template taggate</h3>
<p>Una forma più avanzata di stringhe template sono le stringhe template <em>taggate</em>. Con esse puoi modificare l'output delle stringhe template usando una funzione. Il primo argomento contiene un array di stringhe letterali ("Ciao" e " mondo" in questo esempio). Il secondo, ed ogni argomento dopo il primo, sono i valori delle espressioni di sostituzione ("15" e "50" qui) processate (o a volte detto <em>lavorate</em>). Alla fine, la tua funzione ritorna la stringa manipolata. Non c'è nulla di speciale sul nome tag nel seguente esempio. Il nome della funzione può essere qualsiasi cosa tu voglia.</p>
<pre class="brush: js">var a = 5;
var b = 10;
function tag(strings, ...values) {
console.log(strings[0]); // "Ciao "
console.log(strings[1]); // " mondo "
console.log(values[0]); // 15
console.log(values[1]); // 50
return "Bazinga!";
}
tag`Ciao ${ a + b } mondo ${ a * b }`;
// "Bazinga!"
</pre>
<p>Le funzioni Tag non devono per forza ritornare una stringa, come mostrato nel seguente esempio.</p>
<pre class="brush: js">function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
template`${0}${1}${0}!`('Y', 'A'); // "YAY!"
template`${0} ${'foo'}!`('Ciao', {foo: 'Mondo'}); // "Ciao Mondo!"
</pre>
<h3 id="Stringhe_grezze">Stringhe grezze</h3>
<p>La proprietà speciale <code>raw</code>, disponibile sull'argomento della prima funzione delle stringhe template taggate, ti consente di accedere alle stringhe grezze per come sono state inserite.</p>
<pre class="brush: js">function tag(strings, ...values) {
console.log(strings.raw[0]);
// "stringa testo linea 1 \\n stringa testo linea 2"
}
tag`stringa testo linea 1 \n stringa testo linea 2`;
</pre>
<p>In aggiunta, il metodo {{jsxref("String.raw()")}} esiste per creare stringhe grezze proprio come la funzione template predefinita e contatenazione di stringhe potrebbero creare.</p>
<pre class="brush: js">String.raw`Salve\n${2+3}!`;
// "Salve\n5!"</pre>
<h2 id="Sicurezza">Sicurezza</h2>
<p>Le stringhe template <strong>NON DEVONO</strong> essere costruite da utenti non fidati, poichè hanno accesso a variabili e funzioni.</p>
<pre class="brush: js">`${console.warn("this is",this)}`; // "this is" Window
let a = 10;
console.warn(`${a+=20}`); // "30"
console.warn(a); // 30
</pre>
<h2 id="Specifiche">Specifiche</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-template-literals', 'Template Literals')}}</td>
<td>{{Spec2('ES6')}}</td>
<td>Definizione iniziale. Definita in molte sezioni della specifica: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-template-literals">Template Literals</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tagged-templates">Tagged Templates</a></td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td>Definita in molte sezioni della specifica: <a href="https://tc39.github.io/ecma262/#sec-template-literals">Template Literals</a>, <a href="https://tc39.github.io/ecma262/#sec-tagged-templates">Tagged Templates</a></td>
</tr>
</tbody>
</table>
<h2 id="Compatibilità_browser">Compatibilità browser</h2>
<div>{{CompatibilityTable}}</div>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Caratteristica</th>
<th>Chrome</th>
<th>Edge</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Supporto base</td>
<td>{{CompatChrome(41)}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatGeckoDesktop("34")}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatOpera(28)}}</td>
<td>{{CompatSafari(9)}}</td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>Caratteristica</th>
<th>Android</th>
<th>Chrome for Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>Supporto base</td>
<td>{{CompatNo}}</td>
<td>{{CompatChrome(41)}}</td>
<td>{{CompatGeckoMobile("34")}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatOpera(28)}}</td>
<td>{{CompatSafari(9)}}</td>
</tr>
</tbody>
</table>
</div>
<h2 id="Vedi_anche">Vedi anche</h2>
<ul>
<li>{{jsxref("String")}}</li>
<li>{{jsxref("String.raw()")}}</li>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Grammatica lessica</a></li>
<li><a href="https://gist.github.com/WebReflection/8f227532143e63649804">Stringhe di tipo template in sintassi compatibile con ES3</a></li>
<li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/">"ES6 in profondità: Stringhe template" su hacks.mozilla.org</a></li>
</ul>
|