You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用JavaScript检测字符串是否包含数组中的元素?

解决JavaScript字符串包含数组元素的检测与移除问题

我懂你的痛点——indexOf()确实只能做完全匹配,没法检测字符串里是否包含数组中的子串。要实现你想要的“只要字符串包含数组里任意一个元素就移除它”的需求,可以用数组的some()方法结合字符串的includes()来搞定,具体看下面的方案:

核心思路

  1. some()遍历数组中的每个元素,检查目标字符串是否包含该元素(子串匹配)
  2. 如果检测到匹配,就执行移除操作(比如从存放字符串的集合中过滤掉该字符串)

示例代码

const targetStr = 'amazon video';
const keywordArray = ['video','app','login','care'];

// 检测目标字符串是否包含数组中的任意关键字
const hasMatchingKeyword = keywordArray.some(keyword => targetStr.includes(keyword));

if (hasMatchingKeyword) {
  // 这里以从字符串数组中移除匹配项为例
  let stringList = ['amazon video', 'google app', 'apple login', 'test string'];
  // 过滤掉所有包含数组关键字的字符串
  stringList = stringList.filter(str => !keywordArray.some(keyword => str.includes(keyword)));
  
  console.log(stringList); // 输出: ['test string']
}

额外优化:不区分大小写匹配

如果需要忽略大小写(比如匹配'Video'或者'VIDEO'也生效),可以把两个字符串都转为小写:

const hasMatchingKeyword = keywordArray.some(keyword => 
  targetStr.toLowerCase().includes(keyword.toLowerCase())
);

为什么不用indexOf?

你已经注意到了,myarray.indexOf(senten_1)是在数组里找完全等于senten_1的元素,而不是判断senten_1是否包含数组里的元素,所以自然没法满足你的需求。而includes()是专门用来检测字符串是否包含子串的方法,搭配some()就能实现数组元素的遍历检测。

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

火山引擎 最新活动