美文网首页
es6中字符串的扩展

es6中字符串的扩展

作者: icaojinyu | 来源:发表于2018-12-11 09:50 被阅读0次

    1. 字符串的解构赋值

      let str = 'hello'
      let [a, b, c, d, e] = str
      console.log(a, b, c, d, e) // h e l l o
    
    2. for of...遍历字符串
      let str = 'lewis'
      for(let key of str){
        console.log(key) // l e w i s
      }
    
    3. includes(), startsWith(), endsWith()
      let str = 'hello world'
      console.log(str.includes('hello')) //true
      console.log(str.startsWith('he')) //true
      console.log(str.endsWith('world')) //true
    
    4. repeat()

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

      let str = '我很帅'
      console.log(str.repeat(3)) // 我很帅我很帅我很帅 (重要的事情说三遍)
    
    5. 模板字符串
    • 模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量
    • 如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中
    • 模板字符串中嵌入变量,需要将变量名写在${}之中
    • 大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性
    • 模板字符串之中还能调用函数
      let message = 'hello world'
      let str = `The message is ${message}!`
      console.log(str) // The message is hello world!
    

    相关文章

      网友评论

          本文标题:es6中字符串的扩展

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