美文网首页JavaScript
ES6学习第三节:字符串的扩展

ES6学习第三节:字符串的扩展

作者: ChangLau | 来源:发表于2019-01-10 17:31 被阅读0次
    • 字符串遍历

    for ... of

    // 字符串遍历
    const txt = 'www.coffeecola.cn'
    for (var item of txt) console.log(item)
    
    • includes startsWith endsWith

    includes():返回布尔值,表示是否找到了参数字符串。
    startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
    endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

    // includes startsWith endsWith
    console.log(txt.includes('coffeecola'))
    console.log(txt.startsWith('www'))
    console.log(txt.endsWith('cn'))
    
    • repeat

    repeat方法返回一个新字符串,表示将原字符串重复n次。

    // repeat
    console.log(txt.repeat(0.1))
    console.log(txt.repeat(2))
    // 取整
    console.log(txt.repeat(2.9))
    
    • padStart padEnd

    字符串补全长度的功能

    // padStart padEnd
    console.log(txt.padStart(txt.length + 8, 'https://'))
    console.log(txt.padEnd(txt.length + 8, '/#/login'))
    
    • matchAll

    Node v10.8.0不支持

    var reg = /o/
    console.log(txt.match(reg))
    // Node不支持 v10.8.0
    // console.log(txt.matchAll(reg));
    var reg = /o/g
    console.log(txt.match(reg))
    
    • 字符串模板
    var name = 'ChangLau'
    var str = `
      \`Hello, my Name is ${name}\`
    `
    console.log(str)
    var a = 1,
      b = 2
    // 模板字符串可以进行JS运算
    console.log(`${a} add ${b} equals ${a + b}`)
    
    

    相关文章

      网友评论

        本文标题:ES6学习第三节:字符串的扩展

        本文链接:https://www.haomeiwen.com/subject/jmnarqtx.html