跳至主要內容

检索字符串:includes()、startWith()、endWith()

GuangBo...大约 2 分钟ES6前端字符串方法includesstartWithendWith

在ES5中,如果想要判断一个字符串是否包含另一个字符串,我们一般会使用indexOf0方法。ES6则为我们新增了3种更加简单的方法,如下表所示。

方法说明
A.includes(B)判断A是否包含B
A.startsWith(B)判断A是否以B“开头”
A.endsWith(B)判断A是否以B“结尾”

提示

上面这3种方法最后都会返回一个布尔值,也就是true或false。

语法

A.includes(B, index)
A.startsWith(B, index)
A.endsWith(B, index)

说明

includes()、startsWith()和endsWith()这3个方法的参数都是一样的:

  • 第1个参数表示“被包含的字符串”,
  • 第2个参数表示“检索的位蛋”。其中第2个参数可以省路,如果省路,则表示检索整个字符串。

需要注意的是,这几个方法中第2个参数的含义路有不同:

  • includes()和startsWith()中的第2个参数表示“从第index个字待开始检素”,
  • 而endsWith()中的第2个参数表示“对前index个字符进行检索”。

注意

另外,includes()中的include、startsWith()中的start、endsWith()中的end后面是有一个“s”的,小伙伴们不要写漏了。

示例: includes()

const str = 'Hello ES6'
console.log(str.includes('ES6'))
console.log(str.includes('es6'))
console.log(str.includes('Hello', 0))
console.log(str.includes('Hello', 2))

示例: startsWith()

const str = 'Hello ES6'
console.log(str.startsWith('hello'))
console.log(str.startsWith('Hello'))

示例: endsWith()

const str = 'Hello ES6'
console.log(str.endsWith('ES6'))
console.log(str.endsWith('es6'))
上次编辑于:
贡献者: shaoguangbo
评论
  • 按正序
  • 按倒序
  • 按热度