字符串的includes、startsWith、endsWith

470 阅读1分钟

摘自《Understanding ECMAScript 6》

    const str = 'hello world'
    str.startsWith('hello') // true
    str.startsWith('world') // false
    str.endsWith('hello') // false
    str.endsWith('world') // true
    
    
    str.startsWith('world', 6) // true
    str.startsWith('w', 6) // true
    str.startsWith('orld', 7) // true
    
    str.endsWith('hello', 5) // true
    str.endsWith('hell', 4) // true
    str.endsWith('ell', 4) // true
    
  • includes() 方法,在给定文本存在于字符串中的任意位置时会返回 true ,否则返回 false ;
  • startsWith() 方法,在给定文本出现在字符串起始处时返回 true ,否则返回 false ;
  • endsWith() 方法,在给定文本出现在字符串结尾处时返回 true ,否则返回 false 。

以上方法都接受两个参数,当提供了第二个参数时,includes() 和 startsWith() 方法会从改索引位置开始尝试匹配,会从字符串起始处(从左往右)开始查找;而 endsWith() 方法会将字符串长度减去该参数,从尾部开始(从右往左)开始查找。

第二个参数的作用: 减少了搜索字符串的次数