Tagged Template Literals in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Template literals also allow us to create tagged template literals. The tagged literal is just like a function definition and allows us to parse template literals. The tagged literal doesn’t contain the parenthesis and the tag function gets the array of string values as first argument.The rest of the arguments are then passed to the other related parameters.

Following is the code to implement tagged template literals in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Tagged Template Literals in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to pass the template string using tagged template literal to sampleTag() function</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function sampleTag(strings, name, age, rollNo) {
      let section;
      if (rollNo > 50) {
         section = "A";
      } else {
         section = "B";
      }
      return `${name} roll no: ${rollNo} age :${age} is in section ${section}`;
   }
   let name = "Rohan",
   age = 16,
   rollNo = 22;
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = sampleTag`${name} aged ${age} and roll no ${rollNo} is new in
      the school`;
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

raja
Updated on 22-Jul-2020 07:37:22

Advertisements