MyTetra Share
Делитесь знаниями!
How to interpolate variables in strings in JavaScript, without concatenation?
Время создания: 15.11.2018 12:16
Текстовые метки: javascript variable string interpolate
Раздел: Javascript
Запись: Velonski/mytetra-database/master/base/1542266188bsi5pqe683/text.html на raw.githubusercontent.com

Starting from Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge you can use an ES2015 / ES6 feature called Template Literals and use this syntax:


`String text ${expression}`


Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.


Example:


var a = 5;

var b = 10;

console.log(`Fifteen is ${a + b}.`);

// "Fifteen is 15.


How neat is that?


Bonus:


It also allows for multi-line strings in javascript without escaping, which is great for templates:


return `

<div class="${foo}">

...

</div>

`;


Browser support:


As this syntax is not supported by older browsers (Internet Explorer and Safari <= 8), you may want to use Babel to transpile your code into ES5 to ensure it will run everywhere.


Side note:


Starting from IE8+ you can use basic string formatting inside console.log:


console.log('%s is %d.', 'Fifteen', 15);


// Fifteen is 15.


Don't miss the fact that the template string is delimited with back ticks (`) instead of your normal quote characters. "${foo}" is literally ${foo} `${foo}` is what you actually want


Also there are many transpilers to turn ES6 into ES5 to fixed the compatibility issue!

Так же в этом разделе:
 
MyTetra Share v.0.65
Яндекс индекс цитирования