JavaScript确定一个字符串是否包含在另一个字符串中的四种方法

一、indexOf()

1.定义

indexOf()方法返回String对象第一次出现指定字符串的索引,若未找到指定值,返回-1。(数组同一个概念)

2.语法

str.indexOf(searchValue[, fromIndex])
  • searchValue:字符串对象中被查找的值。
  • fromIndex:开始查找的索引,默认为0。

3.示例

let str = 'Hello, indexOf!';
console.log(str.indexOf('Hello')); // 0
console.log(str.indexOf('indexOf')); // 7
console.log(str.indexOf('l')); // 2
console.log(str.indexOf('l', 2)); // 2 加上开始查找的索引
console.log(str.indexOf('l', 3)); // 3
console.log(str.indexOf('e', 3)); // 10
console.log(str.indexOf('l', 4)); // -1
console.log(str.indexOf('world')); // -1

4.注意

区分大小写

let str = 'Hello, indexOf!';
console.log(str.indexOf('e')); // 1
console.log(str.indexOf('E')); // -1

二、includes()

1.定义

includes()方法判断一个字符串是否包含在另一个字符串中,返回true或false。

2.语法

str.includes(searchString[, position])
  • searchString:要搜索的字符串。
  • position:表示从哪个索引开始搜索,默认为0。

3.示例

let str = 'Hello, includes!';
console.log(str.includes('Hello')); // true
console.log(str.includes('includes')); // true
console.log(str.includes('hello')); // false
console.log(str.includes('Helle')); // false
console.log(str.includes('Helle', 1)); // false
console.log(str.includes('e', 2)); // true

三、startsWith()

1.定义

startsWith()方法用于判断一个字符串是否在另一个字符串的头部,返回true或false。

2.语法

str.startsWith(searchString[, position])

3.示例

let str = 'Hello, startsWith!';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('H')); // true
console.log(str.startsWith('h')); // false
console.log(str.startsWith('startsWith')); // false
console.log(str.startsWith('startsWith', 7)); // true

四、endsWith()

1.定义

endsWith()方法用于判断一个字符串是否在另一个字符串的尾部,返回true或false。

2.语法

str.endsWith(searchString[, length])
  • searchString:要搜索的字符串。
  • length:作为查找字符串(str)的长度,默认是字符串本身的长度。

3.示例

let str = 'Hello, endsWith!';
console.log(str.endsWith('endsWith!')); // true
console.log(str.endsWith('EndsWith!')); // false
console.log(str.endsWith('Hello')); // false
console.log(str.endsWith('end', 10)); // true

JavaScript确定一个字符串是否包含在另一个字符串中的四种方法

posted @   除除  阅读(14506)  评论(2编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示