📌  相关文章
📜  在 javascript 中使用包含查找特定字符串(1)

📅  最后修改于: 2023-12-03 15:07:40.706000             🧑  作者: Mango

在 JavaScript 中使用包含查找特定字符串

在 JavaScript 中,我们经常需要查找字符串中是否包含特定的子字符串。下面是如何使用 JavaScript 来进行包含查找的基本介绍。

方法

JavaScript 提供了两种方法来检测一个字符串是否包含一个子字符串:

  1. indexOf()
  2. includes()
indexOf()

indexOf() 方法返回字符串中子串第一次出现的位置。如果没有找到子串,则返回 -1。

const str = 'Hello, world!';
const subStr = 'world';
const pos = str.indexOf(subStr);

if (pos !== -1) {
  console.log(`Substring found at position ${pos}`);
} else {
  console.log('Substring not found');
}

在上面的示例中,我们使用了 indexOf() 方法来查找字符串 str 中是否包含子串 subStr。如果找到了子串,则会在控制台打印出该子串在原字符串中的位置。

includes()

includes() 方法返回字符串中是否包含指定的子字符串。它返回一个布尔值,如果找到了子串,则返回 true;否则返回 false

const str = 'Hello, world!';
const subStr = 'world';

if (str.includes(subStr)) {
  console.log('Substring found');
} else {
  console.log('Substring not found');
}

在上面的示例中,我们使用了 includes() 方法来查找字符串 str 中是否包含子串 subStr。如果找到了子串,则会在控制台打印出 Substring found

大小写敏感性

在默认情况下,indexOf()includes() 都是大小写敏感的,这意味着它们将区分大小写。

例如,下面的代码将返回 false

const str = 'Hello, World!';
const subStr = 'world';

if (str.includes(subStr)) {
  console.log('Substring found');
} else {
  console.log('Substring not found');
}

要使 indexOf()includes() 方法不区分大小写,可以使用 toLowerCase() 方法或 toUpperCase() 方法将字符串统一转换为小写或大写。

例如,下面的代码将返回 true

const str = 'Hello, World!';
const subStr = 'world';

if (str.toLowerCase().includes(subStr.toLowerCase())) {
  console.log('Substring found');
} else {
  console.log('Substring not found');
}
正则表达式

除了 indexOf()includes() 方法外,我们还可以使用正则表达式来检查一个字符串是否包含一个子字符串。

const str = 'Hello, World!';
const subStr = 'world';
const regExp = new RegExp(subStr, 'i');

if (regExp.test(str)) {
  console.log('Substring found');
} else {
  console.log('Substring not found');
}

在上面的示例中,我们使用了一个正则表达式来检查字符串 str 是否包含子串 subStr,并且通过 i 标志使其不区分大小写。

结论

在 JavaScript 中,使用 indexOf()includes() 方法都可以有效地检查字符串是否包含一个指定的子串。根据情况,可以选择使用大小写敏感或大小写不敏感的方法。我们还可以使用正则表达式来进行更复杂的检查。