ES-6 模版字符串

265 阅读1分钟


es6模板字符简直是开发者的福音啊,解决了ES5在字符串功能上的痛点。 第一个用途,基本的字符串格式化。将表达式嵌入字符串中进行拼接。用${}来界定。  

    //ES5 
    var name = 'nwd'
    console.log('hello' + name)
    //es6
    const name = 'nwd'
    console.log(`hello ${name}`) //hello lux

第二个用途,在ES5时我们通过反斜杠(\)来做多行字符串或者字符串一行行拼接。ES6反引号(``)直接搞定。

    // ES5
    var msg = "Hi \
    man!
    "
    // ES6
    const template = `<div>
        <span>hello world</span>
    </div>`

对于字符串ES6当然也提供了很多厉害也很有意思的方法

 

   // 1.includes:判断是否包含然后直接返回布尔值
    const str = 'nwd'
    console.log(str.includes('w')) // true

    // 2.repeat: 获取字符串重复n次
    const str = 'nwd'
    console.log(str.repeat(3)) // 'nwdnwdnwd'

    //如果你带入小数, Math.floor(num) 来处理
    // s.repeat(3.1) 或者 s.repeat(3.9) 都当做成 s.repeat(3) 来处理

    // 3. startsWith 和 endsWith 判断是否以 给定文本 开始或者结束
    const str =  'hello world!'
    console.log(str.startsWith('hello')) // true
    console.log(str.endsWith('!')) // true