Javascript String Template Raw Strings

Introduction

To get the raw template literal contents from template literals, use the String.raw tag function.

// \u00A9 is the copyright symbol 
console.log(`\u00A9`);            /* w w  w .j a  v a  2  s . co m*/
console.log(String.raw`\u00A9`);  // \u00A9 
           
// Newline demo 
console.log(`first line\nsecond line`);             
console.log(String.raw`first line\nsecond line`);  // "first line\nsecond line" 
           
// This does not work for newline characters
console.log(`first line 
second line`);                 
           
console.log(String.raw`first line 
second line`);                 

The raw values are available as a property on each element in the string piece collection inside the tag function:

function printRaw(strings) { 
   console.log('Actual characters:'); 
   for (const string of strings) { 
      console.log(string); //from  ww w.j a v  a 2 s.com
   } 
           
   console.log('Escaped characters;'); 
   for (const rawString of strings.raw) { 
       console.log(rawString); 
   } 
} 
printRaw`\u00A9${ 'and' }\n`; //Template tag function



PreviousNext

Related