js之match和includes

首先,str1.match(str2)str1.includes(str2)都有找出字符串中是否包含另一个字符串的作用,它们都有一个返回值。
简单介绍它们的不同之处吧!

  1. str1.match(str2); 它能比较str1中是否有str2的字符,若找到,则会返回一个数组,它存储的有str2第一个字符在str1中字符的索引,若没找到,即str1无str2中的元素,则会返回null
    eg:
<script>
        console.log("hello".match("el"));
        console.log("hello".match("elk"));
</script>

结果如图:

在这里插入图片描述
不难理解k元素在"hello"中并没有出现,故返回null值。

应用

这样我们可以利用它做一个indexOf的作用:
找到返回索引;找不到返回-1。

<script>
	function indexOf(str1, str2) {
		var result = str1.match(str2);
		if (result) {
			return result.index; 
		} else {
		return -1;
	}
	console.log(indexof("hello", "el"));
	console.log(indexof("hello", "elk"));
	console.log("hello".indexOf("l"));
</script>

结果如图:
在这里插入图片描述

  1. str1.includes(str2);它也是能找到是否包含另一个字符串的方法,只不过它返回的是一个布尔值,找到字符串返true,反之false
    eg:
	<script>
		console.log("hello".includes("el"));
        console.log("hello".includes("elk"));
	</script>

结果如图:
在这里插入图片描述
最主要的区别是返回值不同,都可以用if来判断2个字符串是否存在包含关系,只不过各自有更细节的效果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值