示例 1:使用 includes() 检查字符串
// program to check if a string contains a substring
// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');
// check if string contains a substring
if(str.includes(checkString)) {
console.log(`The string contains ${checkString}`);
} else {
console.log(`The string does not contain ${checkString}`);
}
输出
Enter a string: JavaScript is fun Enter a string that you want to check: fun The string contains fun
includes()
方法用于与 if...else 语句结合,检查一个字符串是否包含指定字符串的字符。
注意:includes()
方法区分大小写。因此,fun 和 Fun 是不同的。
示例 2:使用 indexOf() 检查字符串
// program to check if a string contains a substring
// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');
// check if string contains a substring
if(str.indexOf(checkString) !== -1) {
console.log(`The string contains ${checkString}`);
} else {
console.log(`The string does not contain ${checkString}`);
}
输出
Enter a string: JavaScript is fun Enter a string that you want to check: fun The string contains fun
在上面的程序中,indexOf()
方法与 if...else
语句结合使用,以检查字符串是否包含子字符串。
indexOf()
方法搜索一个字符串,并返回第一个匹配项的位置。当找不到子字符串时,它返回 -1。
注意:indexOf()
方法区分大小写。
另请阅读