html是否包含字符串,javascript字符串是否包含某字符?

JavaScript中判断字符串中是否包含某字符的方法:1、indexOf()方法,返回第一次出现指定字符串的索引。2、includes()方法,返回true或false。3、startsWith()方法等等。

5d68da69aa03f285.jpg

JavaScript中判断字符串是否包含某字符的方法详解:

一、indexOf()

1.定义

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

2.语法str.indexOf(searchValue[, fromIndex])

searchValue:字符串对象中被查找的值。

fromIndex:开始查找的索引,默认为0。

示例: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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值