indexOf()、includes()、startsWith()、endsWith()

是否包含字符串三种新方法


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

  • includes():返回布尔值,表示是否找到了参数字符串。
  • startsWith():返回布尔值,表示参数字符串是否在源字符串的头部。
  • endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部。
  1. var str = "Hello world!";
  2.  
  3. str.startsWith("Hello") // true
  4. str.endsWith("!") // true
  5. str.includes("o") // true

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

  1. var str = "Hello world!";
  2.  
  3. str.startsWith("world", 6) // true
  4. str.endsWith("Hello", 5) // true
  5. str.includes("Hello", 6) // false

上面代码表示,使用第二个参数n时,endsWith 的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。

posted @ 2017-12-13 14:02  年少的你如此美丽  阅读(234)  评论(0编辑  收藏  举报