You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript检测字符串中是否包含一个或多个指定字符串?

改进你的contains函数以支持多单词检测

首先得指出你原函数里的一个明显问题:循环第一次迭代就直接返回结果了!比如如果输入是'world hello',你要查找'hello',函数会因为第一个单词是world就直接返回false,根本不会检查后面的单词,这连单个单词的检测都做不对。

接下来咱们一步步修改,让它既能支持单个单词,又能支持多单词数组的检测。我会分两种常用场景来写,你可以根据需求选:


场景1:只要有一个目标单词存在就返回true(任意匹配)

这个版本会检查输入字符串中是否包含目标列表里的任意一个单词:

// 给String原型添加contains方法
String.prototype.contains = function(targets) {
  // 把输入字符串拆成单词数组,用/\s+/处理多个空格的情况,同时去掉首尾空格
  const inputWords = this.trim().split(/\s+/);
  // 统一处理目标:如果是单个字符串就转成数组,方便后续统一逻辑
  const targetList = Array.isArray(targets) ? targets : [targets];
  
  // 用some方法检查:只要有一个目标单词在输入数组里,就返回true
  return targetList.some(word => inputWords.includes(word));
};

// 测试用例
console.log('hello me want coffee'.contains('hello')); // true
console.log('hello me want coffee'.contains(['hello','want'])); // true
console.log('hello me want coffee'.contains(['hello','tea'])); // true(因为hello存在)
console.log('hello   me   want coffee'.contains('me')); // true(处理了多空格)

场景2:所有目标单词都必须存在才返回true(全匹配)

如果你的需求是必须所有传入的单词都在输入里,就把上面的some换成every:

String.prototype.contains = function(targets) {
  const inputWords = this.trim().split(/\s+/);
  const targetList = Array.isArray(targets) ? targets : [targets];
  
  // 用every方法检查:只有所有目标单词都在输入数组里,才返回true
  return targetList.every(word => inputWords.includes(word));
};

// 测试用例
console.log('hello me want coffee'.contains(['hello','want'])); // true
console.log('hello me want coffee'.contains(['hello','tea'])); // false(tea不存在)
console.log('hello me want coffee'.contains(['me','coffee'])); // true

额外说明

  1. 我把Str.prototype改成了String.prototype,因为原生字符串的构造函数是String,不是Str,之前的写法会报错。
  2. 调用方式要注意:应该用字符串实例直接调用方法,比如'your string here'.contains(['word1','word2']),而不是直接调用原型上的方法传参。
  3. 用trim().split(/\s+/)代替split(' ')是为了处理输入中存在多个连续空格的情况,避免产生空字符串元素影响检测结果。

内容的提问来源于stack exchange,提问作者okky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:04:54