如何在JavaScript中检查字符串是否包含子字符串?

Given a string, substring and we have to check whether a string contains a substring or not?

给定一个字符串,子字符串,我们必须检查一个字符串是否包含一个子字符串?

检查字符串是否包含子字符串 (Checking string contains substring or not)

There are two popular ways to check whether a substring exists in a string or not?

有两种流行的方法来检查字符串中是否存在子字符串?

  1. Using JavaScript includes() method

    使用JavaScript include()方法

  2. Using JavaScript indexOf() method

    使用JavaScript indexOf()方法

1) Using JavaScript includes() method

1)使用JavaScript include()方法

includes() method is a string method in JavaScript, it returns true if the string contains a substring or not?

include()方法是JavaScript中的字符串方法,如果该字符串包含子字符串,它是否返回true?

Syntax:

句法:

    string.includes(substring);

JavaScript Code to check whether a string contains a substring or not using includes() method:

JavaScript代码使用include()方法检查字符串是否包含子字符串:

<script>
	var str = "Hello world!";
	var substr = "Hello";
	if(str.includes(substr)==true){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}

	substr = "Okay";
	if(str.includes(substr)==true){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}		
</script>

Output

输出量

Hello world! contains Hello
Hello world! does not contain Okay

2) Using JavaScript indexOf() method

2)使用JavaScript indexOf()方法

indexOf() is a string method in JavaScript, if substring founds in the string - it returns the starting position of the substring if substring does not found in the string – it returns -1.

indexOf()是JavaScript中的字符串方法,如果在字符串中找到子字符串-如果在字符串中未找到子字符串,则返回子字符串的起始位置-返回-1 。

Syntax:

句法:

    string.indexOf(substring);

JavaScript Code to check whether a string contains a substring or not using indexOf() method:

JavaScript代码使用indexOf()方法检查字符串是否包含子字符串:

<script>
	var str = "Hello world!";
	var substr = "Hello";
	if(str.indexOf(substr) != -1){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}

	substr = "Okay";
	if(str.indexOf(substr) != -1){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}		
</script>

Output

输出量

Hello world! contains Hello
Hello world! does not contain Okay


翻译自: https://www.includehelp.com/code-snippets/check-whether-a-string-contains-a-substring-in-javascript.aspx

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值