Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

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

用于检查字符串是否包含子字符串的 JavaScript 程序

在这个例子中,您将学习编写一个 JavaScript 程序来检查一个字符串是否包含一个子字符串。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 字符串 Javascript 字符串包含() JavaScript String indexOf()

示例 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() 方法区分大小写。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4