示例 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() 方法区分大小写。因此,乐趣和乐趣是不同的。
示例 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() 方法区分大小写。