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个字符串是否存在包含关系,只不过各自有更细节的效果。

猜你喜欢

转载自blog.csdn.net/qq_48784569/article/details/107377662
今日推荐