JavaScript 程序:检查字符串是否包含子字符串

要理解此示例,您应了解以下 JavaScript 编程 主题


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


示例 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() 方法区分大小写。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战