跳到主要内容

解释ES6 includes(), startsWith(), endsWith()?

参考答案:

ES6(ECMAScript 2015)为字符串对象引入了几个新的方法,其中包括 includes(), startsWith(), 和 endsWith()。这些方法提供了更直观和易用的方式来检查字符串中是否包含某个子字符串,或者字符串是否以/结束于某个子字符串。

  1. includes():

    • 用途:检查一个字符串是否包含另一个字符串。
    • 语法:str.includes(searchValue[, position])
    • 返回值:如果字符串包含指定的子字符串,则返回 true,否则返回 false
    • 例子:
    	javascript`let str = "Hello, World!";
    	console.log(str.includes("World"));  // true
    	console.log(str.includes("Earth"));  // false
    	console.log(str.includes("Hello", 7));  // false, 因为从索引7开始不再包含"Hello"`
    
  2. startsWith():

    • 用途:检查一个字符串是否以指定的子字符串开始。
    • 语法:str.startsWith(searchValue[, position])
    • 返回值:如果字符串以指定的子字符串开始,则返回 true,否则返回 false
    • 例子:
    	javascript`let str = "Hello, World!";
    	console.log(str.startsWith("Hello"));  // true
    	console.log(str.startsWith("World"));  // false
    	console.log(str.startsWith("o", 5));  // true, 因为从索引5开始确实是"o"`
    
  3. endsWith():

    • 用途:检查一个字符串是否以指定的子字符串结束。
    • 语法:str.endsWith(searchValue[, position])
    • 返回值:如果字符串以指定的子字符串结束,则返回 true,否则返回 false
    • 例子:
    	javascript`let str = "Hello, World!";
    	console.log(str.endsWith("World!"));  // true
    	console.log(str.endsWith("Hello"));  // false
    	console.log(str.endsWith("l", 12));  // true, 因为到索引12为止确实是"l"`
    

对于 includes(), startsWith(), 和 endsWith() 方法,它们都可以接受一个可选的 position 参数,该参数表示开始搜索的起始位置。如果没有提供此参数,那么搜索将从字符串的开始位置开始。

这些方法在进行字符串匹配时,都是大小写敏感的。如果需要执行大小写不敏感的匹配,可以先将字符串转换为全小写或全大写,然后再使用这些方法。