ES6字符串

123 阅读1分钟
  • 字符串遍历for...of...

    for (let codePoint of 'foo') {
      console.log(codePoint)
    }
    // "f"
    // "o"
    // "o"
    
  • 模板字符串

    // 字符串中嵌入变量
    let name = "Bob", time = "today";
    `Hello ${name}, how are you ${time}?`
    
  • includes(), startsWith(), endsWith()

    传统上,JavaScript 只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6 又提供了三种新方法。

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

     let s = 'Hello world!';
     s.startsWith('Hello') // true
     s.endsWith('!') // true
     s.includes('o') // true

这三个方法都支持第二个参数,表示开始搜索的位置。

      let s = 'Hello world!';

      s.startsWith('world', 6) // true
      s.endsWith('Hello', 5) // true
      s.includes('Hello', 6) // false
  • repeat()

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

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
  • trim,  trimStart(),trimEnd()

    trimStart()trimEnd()这两个方法。它们的行为与trim()一致,trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。

    const s = '  abc  ';
    
    s.trim() // "abc"
    s.trimStart() // "abc  "
    s.trimEnd() // "  abc"
    

    上面代码中,trimStart()只消除头部的空格,保留尾部的空格。trimEnd()也是类似行为。

    除了空格键,这两个方法对字符串头部(或尾部)的 tab 键、换行符等不可见的空白符号也有效。

    浏览器还部署了额外的两个方法,trimLeft()trimStart()的别名,trimRight()trimEnd()的别名。