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
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