Javascript String Template Interpolation

Introduction

Java String template literals support for interpolation.

This can be accomplished using a JavaScript expression inside ${}:

let value = 5; /* www .j  av  a2s.  c o  m*/
let exponent = 'second'; 
              
// Formerly, interpolation was accomplished as follows: 
let interpolatedString =  value + ' to the ' + exponent + ' power is ' + (value * value); 
// The same thing accomplished with template literals: 
let interpolatedTemplateLiteral = `${ value } to the ${ exponent } power is ${ value * value }`; 
            
console.log(interpolatedString);           // 5 to the second power is 25 
console.log(interpolatedTemplateLiteral);  // 5 to the second power is 25 

Nesting template strings is safe with no escaping required:

console.log(`Hello, ${ `World` }!`);  // Hello, World! 

toString() is invoked to coerce expression result into string:

let foo = { //  ww  w .  j  av  a2 s.com
      toString: () => 'World' 
}; 
console.log(`Hello, ${ foo }!`);      // Hello, World! 

Invoking functions and methods inside interpolated expressions is allowed:

function capitalize(word) { 
   return `${ word[0].toUpperCase() }${ word.slice(1) }`; 
} 
console.log(`${ capitalize('hello') }, ${ capitalize('world') }!`);  // Hello, World! 

Templates can safely interpolate their previous value:

let value = ''; 
function append() { 
   value = `${value}abc` //  w ww  . ja  va 2s. c  o  m
   console.log(value); 
} 
append();  // abc 
append();  // abcabc 
append();  // abcabcabc 



PreviousNext

Related