js 字符串方法 contains
时间: 2023-11-10 07:50:28 浏览: 51
JavaScript中没有字符串方法叫做 `contains`。但是你可以使用 `includes` 方法来判断一个字符串是否包含另一个子字符串。下面是使用 `includes` 方法的示例:
```javascript
const str = 'Hello, world!';
console.log(str.includes('Hello')); // true
console.log(str.includes('hello')); // false
console.log(str.includes('world')); // true
console.log(str.includes('foo')); // false
```
`includes` 方法返回一个布尔值,如果字符串包含指定的子字符串,则返回 `true`,否则返回 `false`。注意,`includes` 方法在判断子字符串时是区分大小写的。如果你想忽略大小写,可以先将字符串转换为小写或大写,然后再进行判断。
相关问题
js包含字符串判断
你可以使用 JavaScript 中的 `includes()` 方法来判断一个字符串是否包含另一个字符串。这个方法接受一个字符串作为参数,如果该字符串包含在原字符串中,则返回 `true`,否则返回 `false`。以下是一个示例:
```
const str = 'Hello, World!';
const substr = 'World';
if (str.includes(substr)) {
console.log('The string contains the substring.');
} else {
console.log('The string does not contain the substring.');
}
```
在上面的示例中,我们检查 `str` 是否包含 `substr`,如果是,则输出字符串包含子字符串的消息,否则输出字符串不包含子字符串的消息。
js判断字符串是否包含
可以使用JavaScript中的`includes()`方法来判断一个字符串是否包含另一个字符串。
例如,以下代码将检查字符串`str`是否包含字符串`substr`:
```
var str = "Hello, world!";
var substr = "world";
if (str.includes(substr)) {
console.log("The string contains the substring");
} else {
console.log("The string does not contain the substring");
}
```
输出结果将是`The string contains the substring`,因为字符串`"Hello, world!"`包含子字符串`"world"`。