JavaScript - 模板字面量



JavaScript 模板字面量

在 JavaScript 中,模板字面量是在 ES6 中引入的,用于动态自定义字符串。模板字面量允许您将变量或表达式添加到字符串中,并且字符串会根据变量和表达式的值变化而变化。

模板字面量有多个同义词。例如,模板字符串、字符串模板、反引号语法等。

语法

请遵循以下语法在 JavaScript 中使用模板字面量。

let str = `Hi ${name}`;

您需要在反引号 (``) 之间编写字符串。要将动态变量或表达式与字符串一起使用,需要将其放在 ${} 之间。

此外,使用模板字面量,您不需要转义字符来在字符串中添加单引号或双引号。

示例

示例:使用模板字面量创建字符串

在下面的示例中,我们使用模板字面量创建了一个包含特殊字符的字符串。

str1 字符串与我们使用单引号或双引号创建的常规字符串相同。str2 字符串包含带有字符串的单引号。在这里,您可以看到我们没有使用转义字符在字符串中添加单引号。

<html>
<body>
   <div id = "output1"> </div>
   <div id = "output2"> </div>
   <script>
      let str1 = `Hello Users!`;
      let str2 = `'Tutorialspoint' is a good website`;
      document.getElementById("output1").innerHTML = str1;
      document.getElementById("output2").innerHTML = str2;
   </script>
</body>
</html>

输出

Hello Users!
'Tutorialspoint' is a good website

示例:带模板字面量的变量

以下代码演示了如何通过将变量传递到模板字面量字符串中,在字符串中使用动态值。

在这里,我们定义了与汽车相关的变量。之后,我们使用模板字面量创建一个字符串并添加变量。

在输出中,您可以看到变量已在字符串中替换为其值。

<html>
<body>
   <p id = "output"> </p>
   <script>
      let car = "BMW";
      let model = "X5";
      const price = 5000000;
      const carStr = `The price of the ${car} ${model} is ${price}.`;
      document.getElementById("output").innerHTML = carStr;
   </script>
</body>
</html>

输出

The price of the BMW X5 is 5000000.

示例:带模板字面量的表达式

您还可以使用模板字面量将表达式添加到字符串中。

在 str1 字符串中,我们添加了表达式以在模板字面量字符串中执行两个数字的求和。

在 str2 中,我们将函数调用作为表达式调用。它将表达式替换为函数返回的值。

<html>
<body>
   <div id = "output1"> </div>
   <div id = "output2"> </div>
   <script>
      function func() {
         return 10;
      }
       
      const str1 = `The sum of 2 and 3 is ${2 + 3}.`;
      const str2 = `The return value from the function is ${func()}`;
      
      document.getElementById("output1").innerHTML = str1;
      document.getElementById("output2").innerHTML = str2;
   </script>
</body>
</html>

输出

The sum of 2 and 3 is 5.
The return value from the function is 10

JavaScript 嵌套模板字面量

JavaScript 允许您在其他模板字面量内部使用模板字面量,这称为嵌套模板字面量。

示例

在下面的示例中,我们在外部模板字面量中添加了表达式。该表达式包含三元运算符。它检查 2 是否小于 3。根据返回的布尔值,它执行第一个或第二个嵌套表达式并打印结果。

<html>
<head>
   <title>Nested Template Literals</title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const nested = `The subtraction result is: ${2 < 3 ? `${3 - 2}` : `${2 - 3}`}`;
      document.getElementById("output").innerHTML = nested;
</script>
</body>
</html>

输出

The subtraction result is: 1

示例:使用模板字面量创建多行字符串

您也可以使用模板字面量来定义多行字符串。

<html>
<body>
   <div id = "output"> </div>
   <script>
      function func() {
         return 10;
      }
      
      const str1 = `The sum of 2 and 3 is ${2 + 3}. <br>
      The return value from the function is ${func()}`;
      
      document.getElementById("output").innerHTML = str1;
   </script>
</body>
</html>

输出

The sum of 2 and 3 is 5.
The return value from the function is 10
广告

© . All rights reserved.