使用模板字串在 JavaScript 中格式化字串


以下是使用 Javascript 中的模板字串來格式化字串的程式碼 −

示例

 線上演示

<!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,
   .sample {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Formatted Strings Using Template Strings JavaScript</h1>
<div class="sample">
`The person name is ${personObj.name}. His age and rollno are
${personObj.age} and ${personObj.rollno} respectively`
</div>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see the template string formatted with the
personObj values</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let personObj = { name: "Rohan Sharma", age: 12, rollno: 22 };
   let arr = [22, 55, 11, 19, 55];
   BtnEle.addEventListener("click", (event) => {
      resEle.innerHTML = `The person name is ${personObj.name}. His age and rollno are
      ${personObj.age} and ${personObj.rollno} respectively`;
   });
</script>
</body>
</html>

輸出

點選“單擊此處”按鈕後 −

更新時間:2020 年 7 月 18 日

230 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始學習
廣告