MUstar

Javascript ES6 Example - Template Strings

Aug 6th, 2018
74
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. if(`\`` === "`"){
  2.     console.log(true);
  3. }
  4.  
  5.  
  6. //Multi-line strings
  7. console.log("string text line 1 \nstring text line2");
  8.  
  9. console.log(`string text line1
  10. string text line2`);
  11.  
  12. //Expression interpolation
  13. var a = 5;
  14. var b = 10;
  15. console.log("Fifteen is" + ( a + b ) + " and\nnot " + (2 * a + b) + "." );
  16.  
  17. console.log(`Fifteen is ${ a + b } and
  18. not ${ 2 * a + b }`);
  19.  
  20. //Nesting templates
  21. function isLargeScreen(){
  22.     return false;
  23. }
  24. var item = {'isCollapsed' : true};
  25.  
  26. var classes = 'header ';
  27. classes += (isLargeScreen() ? '' : item.isCollapsed ? 'icon-expander' : ' icon-collapser');
  28. console.log(classes);
  29.  
  30. const classes2 = `header ${isLargeScreen() ? '' :
  31.     (item.isCollapsed ? 'icon-expander' : 'icon-collapser')}`;
  32. console.log(classes2);
  33.  
  34. const classes3 = `header ${isLargeScreen() ? '' :
  35.     `icon-${item.isCollapsed ? 'expander' : 'collapser'}`}`;
  36. console.log(classes3);
  37.  
  38. //Tagged templates
  39. var person = "Mike";
  40. var age = 28;
  41.  
  42. function myTag(strings, personExp, ageExp) {
  43.     var str0 = strings[0];
  44.     var str1 = strings[1];
  45.  
  46.     var ageStr;
  47.     if(ageExp > 99){
  48.         ageStr = 'centenarian';
  49.     } else {
  50.         ageStr = 'youngster';
  51.     }
  52.  
  53.     return str0 + personExp + str1 + ageStr;
  54. }
  55.  
  56. var output = myTag`that ${person} is a ${age}`;
  57. console.log(output);
  58.  
  59. function template(strings, ...keys){
  60.     return (function(...values){
  61.         var dict = values[values.length - 1] || {};
  62.         var result = [strings[0]];
  63.         keys.forEach(function (key, i) {
  64.             var value = Number.isInteger(key) ? values[key] : dict[key];
  65.             result.push(value,strings[i + 1]);
  66.         });
  67.         return result.join('');
  68.     });
  69. }
  70.  
  71. var t1Closure = template `${0}${1}${0}!`;
  72. console.log(t1Closure('Y','A'));
  73. var t2Closure = template `${0}${'foo'}!`;
  74. console.log(t2Closure('Hello ',{foo : 'World'}));
  75.  
  76. //Raw string
  77. function tag(strings){
  78.     console.log(strings);
  79.     console.log(strings.raw[0]);
  80. }
  81. tag`string text line1 \n string text line2`;
  82. tag`Hello World! \r Welcome to The World`;
  83.  
  84. var str = String.raw`Hi\n${2+3}!`;
  85. console.log(str);
  86. console.log(str.length);
  87. console.log(str.split('').join(','));
  88.  
  89. //Tagged templates and escape sequences
  90. latex`\uincode`;
  91.  
  92.  
  93. function latec
RAW Paste Data