js 判断是否包含某个字符串

js 判断是否包含某个字符串

js 判断是否包含某个字符串

JavaScript 中,我们经常会遇到需要判断一个字符串是否包含另一个字符串的情况。这样的判断通常用于搜索、筛选和验证用户输入等场景。在本文中,我们将介绍几种判断字符串是否包含某个子字符串的方法,并分别进行示例演示。

方法一:使用 includes() 方法

JavaScript 中的字符串对象提供了 includes() 方法,用于判断一个字符串是否包含另一个字符串。includes() 方法返回一个布尔值,表示是否找到了被搜索的子字符串。

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

if (str.includes(subStr)) {
  console.log(`'{str}' 包含子字符串 '{subStr}'`);
} else {
  console.log(`'{str}' 不包含子字符串 '{subStr}'`);
}

运行结果:

'Hello, world!' 包含子字符串 'world'

方法二:使用 indexOf() 方法

另一种常见的判断字符串包含子字符串的方法是使用字符串对象的 indexOf() 方法。indexOf() 方法返回被搜索字符串的第一个出现位置的索引,如果未找到则返回 -1。

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

if (str.indexOf(subStr) !== -1) {
  console.log(`'{str}' 包含子字符串 '{subStr}'`);
} else {
  console.log(`'{str}' 不包含子字符串 '{subStr}'`);
}

运行结果:

'Hello, world!' 包含子字符串 'world'

方法三:使用正则表达式

正则表达式是强大的模式匹配工具,在 JavaScript 中也可以用来判断一个字符串是否包含某个子字符串。我们可以使用 test() 方法来判断字符串是否匹配某个模式。

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

if (subStr.test(str)) {
  console.log(`'{str}' 包含子字符串 'world'`);
} else {
  console.log(`'{str}' 不包含子字符串 'world'`);
}

运行结果:

'Hello, world!' 包含子字符串 'world'

方法四:使用 startsWith() 和 endsWith() 方法

除了上述方法外,JavaScript 字符串对象还提供了 startsWith()endsWith() 方法,用于判断一个字符串是否以某个子字符串开始或结束。

const str = 'Hello, world!';
const startsWithStr = 'Hello';
const endsWithStr = 'world!';

if (str.startsWith(startsWithStr)) {
  console.log(`'{str}' 以 '{startsWithStr}' 开头`);
} else {
  console.log(`'{str}' 不以 '{startsWithStr}' 开头`);
}

if (str.endsWith(endsWithStr)) {
  console.log(`'{str}' 以 '{endsWithStr}' 结尾`);
} else {
  console.log(`'{str}' 不以 '{endsWithStr}' 结尾`);
}

运行结果:

'Hello, world!' 以 'Hello' 开头
'Hello, world!' 以 'world!' 结尾

总结

在 JavaScript 中,我们可以使用 includes()indexOf()、正则表达式、startsWith()endsWith() 等方法来判断一个字符串是否包含某个子字符串。根据实际需求和编程习惯,选择合适的方法进行字符串包含判断十分重要。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程