📌  相关文章
📜  js 检查字符串是否包含字符 - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:32.449000             🧑  作者: Mango

检查字符串是否包含字符 - JavaScript

在 JavaScript 中,我们可以使用以下方法来检查一个字符串中是否包含指定的字符:

  1. includes() 方法:这个方法用来判断一个字符串是否包含指定的字符,返回值为 truefalse
const str = 'hello world';

console.log(str.includes('world')); // true
console.log(str.includes('john')); // false
  1. indexOf() 方法:这个方法返回指定字符在字符串中第一次出现的位置,如果没有找到,返回 -1
const str = 'hello world';

console.log(str.indexOf('world')); // 6
console.log(str.indexOf('john')); // -1
  1. 正则表达式:可以使用正则表达式来匹配字符串中是否包含指定的字符。
const str = 'hello world';

console.log(/world/.test(str)); // true
console.log(/john/.test(str)); // false

除此之外,我们还可以使用 search() 方法来查找指定字符在字符串中第一次出现的位置,使用 match() 方法来返回一个数组,包含所有匹配的子字符串。

有时候,在判断一个字符串是否包含指定字符的同时,需要忽略大小写,这时候我们可以将字符串和字符都转换为小写或大写来进行比较。

const str = 'Hello World';

console.log(str.toLowerCase().includes('world')); // true
console.log(str.toUpperCase().includes('world')); // true

以上是 JavaScript 中检查字符串是否包含指定字符的方法,具体使用哪种方法取决于情况。