详解ES6新增字符串扩张方法includes()、startsWith()、endsWith()

作者:小括号

时间:2026-10-23

浏览:365

本文详细介绍ES6新增的三种字符串查找方法:includes、startsWith和endsWith。它们分别用于判断字符串是否包含子串、是否以指定子串开头或结尾,并返回布尔值。所有方法均支持第二个参数指定搜索起始位置,相比传统的indexOf方法更加直观易用。

文章目录

ES6字符串新方法简介

当有人询问如何确定一个字符串是否包含在另一个字符串中时,我们通常会立即想到 indexOf 方法。实际上,ES6 引入了三种新的字符串方法includes()、startsWith()、endsWith(),它们同样非常实用。

这里不再赘述 indexOf 方法,因为它广为人知:它返回给定元素在数组中第一次出现的位置,即匹配开始的位置;如果未找到,则返回 -1。

下面详细介绍 ES6 新增的这三种方法:

includes()方法详解

①includes():返回布尔值,表示是否找到了参数字符串。

如下所示:


let str = 'Hello world!';
let res1 = str.includes('Hello');
let res2 = str.includes('hi');
console.log(res1); // true
console.log(res2); // false

结果:

ES6字符串新方法简介

startsWith()方法详解

②startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。

如下所示:


let str = 'Hello world!';
let res1 = str.startsWith('Hello');
let res2 = str.startsWith('world');
console.log(res1); // true
console.log(res2); // false

结果:

ES6字符串新方法简介

endsWith()方法详解

③endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

如下所示:


let str = 'Hello world!';
let res1 = str.endsWith('!');
let res2 = str.endsWith('d');
console.log(res1); // true
console.log(res2); // false

结果:

ES6字符串新方法简介

第二个参数说明

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


 let str = 'Hello World!'
 console.log(str.includes('World', 5)) // true 从索引5(包含索引5)开始搜索
 console.log(str.includes('World', 7)) // false
 console.log(str.startsWith('lo', 3)) // true
 console.log(str.startsWith('H', 3)) // false
 console.log(str.endsWith('Hel', 3)) // true
 console.log(str.endsWith('d', 3)) // false

到此这篇关于详解ES6新增字符串扩张方法includes()、startsWith()、endsWith()的文章就介绍到这了,更多相关ES6 includes() startsWith() endsWith()内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章