Javascript String Template Literals

Introduction

Javascript can define strings using template literals.

Javascript template literals respect new line characters, and can be defined spanning multiple lines:

let myMultiLineString = 'first line\nsecond line'; 
let myMultiLineTemplateLiteral = `first line 
second line`; /* w  w w  .ja  v a 2  s . com*/
            
console.log(myMultiLineString);   
console.log(myMultiLineTemplateLiteral);    
console.log(myMultiLineString === myMultiLinetemplateLiteral);

Javascript template literals are useful when defining templates, such as HTML:

let pageHTML = ` 
            <div> 
              <a href="#"> 
                <span>span</span> 
              </a> 
            </div>`; 
let myTemplateLiteral = `first line 
                         second line`; /* w ww  . ja v a2 s  .  co m*/
console.log(myTemplateLiteral.length); 
// This template literal begins with a line return character 

let secondTemplateLiteral = ` 
first line 
second line`; 

console.log(secondTemplateLiteral[0] === '\n');



PreviousNext

Related