JavaScript - Template (literals|strings)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

Template literals are string literals allowing embedded expressions.

Template literals enables:

in the same syntactic sugar than a bash expression.

Advertising

3 - Syntax

Template literals:

  • are enclosed by the back-tick
  • can contain place holders. These are indicated by the Dollar sign and curly braces ${expression}
  • can be tagged. They allow to parse template literals with a function.

\ is the escape character in template literals.

4 - Example

4.1 - Variable Substitution

variable substitution

var name='Nico';
console.log(`Hello ${name}`);

4.2 - Back-tick Equality

console.log(`\`` === '`')

4.3 - MultiLine

Without Template literals

console.log('string text line 1\n' +
'string text line 2');

With Template literals

console.log(`string text line 1
string text line 2`);

Advertising

4.4 - Concatenation vs Expression Substitution

Without Template literals

var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + 
' and\nnot ' + (2 * a + b) + '.');

With Template literals

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

4.5 - Tag

4.5.1 - Named Variable

var person = 'Nico'; // ${person}
var yearsOfExperience = 1; // ${yearsOfExperience}
 
var output = myTagFunction`that ${person} is a ${yearsOfExperience} in Javascript`; 
// that Nico is a NewBie in Javascript
console.log(output);
 
function myTagFunction(strings, personExp, yearExp) {
 
  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "
  var str2 = strings[2]; // " in Javascript "
 
  if (yearExp> 3){
    levelStr = 'Medior';
  } else {
    levelStr = 'Newbie';
  }
 
  return str0 + personExp + str1 + levelStr + str2;
 
}

4.5.2 - Unamed Variable (Positional and Inline)

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('');
  });
}
 
var t1Closure = template`${0}${1}${0}!`;
console.log(t1Closure('Y', 'A'));  // "YAY!"
var t2Closure = template`${0} ${'foo'}!`;
console.log(t2Closure('Hello', {foo: 'World'}));  // "Hello World!"

5 - Documentation / Reference

Advertising
web/javascript/es/template.txt · Last modified: 2019/05/14 11:29 by gerardnico