ES6—模板字符串

296 阅读1分钟

1.概述

模板字符串(template string)是以反引号(``)作为标识的一个增强版字符串。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板字符串</title>
</head>
<body>
    <script>
        //一、认识模板字符串
        //一般字符串
        const username1='alex';
        "alex"
        //模板字符串
        const username2=`alex`;            //(1)普通字符串
        console.log(username1,username2);  //alex alex
        console.log(username1===username2);  //true

        //二、模板字符串与一般字符串的区别
        const person ={
            username:'alex',
            age:18,
            sex:'male'
        };
        // const info='我的名字是:'+person.username+', 性别是:'+person.sex+', 今年'+person.age+'岁了';   //一般字符串:字符串拼接
        const info=`我的名字是:${person.username}, 性别是:${person.sex}, 今年${person.age}岁了`;  //模板字符串,输出“我的名字是:alex, 性别是:male, 今年18岁了”
        console.log(info);
    </script>
</body>
</html>

总结:当和其他东西一起使用时,使用模板字符串,方便注入

2.模板字符串的注意事项

1)输出多行字符串

//1.输出多行字符串
 const info = '第1行\n第2行';   //一般字符
 console.log(info);

 const info1 = `第1行\n第2行`;  //模板字符串
 const info2 = `第1行          //(2)定义多行字符串
第2行`;                         //若前面有多个空格,控制台会原样输出
 console.log(info);

注意:模板字符串中,所有的空格、换行或缩进都会被保留在输出之中。

2)输出 ` 和 \ 等特殊字符

//2.输出`和\等特殊字符
const info = ```;    //错误写法
const info = `\`\\`;      //` \  加个反斜杠\将`和\转义成普通字符
console.log(info);

3)模板字符串的注入

//*3.模板字符串的注入
//${}
const username = 'alex';
const person = {age:18,sex:'male'};
const getSex = function(sex){
     return sex==='male'?'男':'女';
};

const info = `${username},${person.age},${getSex(person.sex)}`;  //(3)在字符串中嵌入变量   alex,18,男  
// const info = `${username},${person.age + 2},${getSex(person.sex)}`;  //alex,20,男
console.log(info);

注意:只要最终可以得出一个值的就可以通过 ${} 注入到模板字符串中。

es6.ruanyifeng.com/?search=%E6…