ES6相关知识点以及实际应用(二)模板字符串

87 阅读1分钟

什么是模板字符串?

模板字符串相当于加强版的字符串,用反引号 "`",插入变量时使用${变量名},除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式.

demo

    <div class="box"></div>
    const oBox = document.querySelector('.box');
    let id = 1, name = '丁真';
    let htmlStr = `
    <ul>
        <li>
            <p id=${id}>${name}</p>
        </li>
    </ul>
    `;
    oBox.innerHTML = htmlStr;

基本用法

普通字符串

    let string = `Hello'\n'world`;
    console.log(string); 
    // Hello'
    // 'world

多行字符串

    let string1 =  `Hey,
    can you stop angry now?`;
    console.log(string1);
    // Hey,
    // can you stop angry now?

字符串插入变量和表达式,变量名写在 ,{} 中,{} 中可以放入 JavaScript 表达式.

    let name = "Mike";
    let age = 27;
    let info = `My Name is ${name},I am ${age+1} years old next year.`
    console.log(info);
    // My Name is Mike,I am 28 years old next year.

字符串中调用函数

    function f(){
      return "have fun!";
    }
    let string2= `Game start,${f()}`;
    console.log(string2);  
    // Game start,have fun!

模板字符串中的换行和空格都是会被保留的

    innerHtml = `
    <ul>
      <li>menu</li>
      
      <li>mine</li>
    </ul>
    `;
    console.log(innerHtml);
    // 输出
    <ul>
     <li>menu</li>
     
     <li>mine</li>
    </ul>