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

