详解ES6新增字符串扩张方法includes()、startsWith()、endsWith()
本文详细介绍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
结果:

startsWith()方法详解
②startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
如下所示:
let str = 'Hello world!';
let res1 = str.startsWith('Hello');
let res2 = str.startsWith('world');
console.log(res1); // true
console.log(res2); // false
结果:

endsWith()方法详解
③endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
如下所示:
let str = 'Hello world!';
let res1 = str.endsWith('!');
let res2 = str.endsWith('d');
console.log(res1); // true
console.log(res2); // false
结果:

第二个参数说明
这三个方法都支持第二个参数,表示开始搜索的位置。
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()内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
