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

如何实现移除字符串中数组内所有指定关键词的JavaScript函数?

解决JavaScript移除字符串中所有指定关键词的问题

问题分析

你写的函数只移除了最后一个关键词,核心原因是pop()只会取出数组的最后一个元素,且仅执行了一次replace操作,自然没法处理所有关键词。下面给你两种实用的解决方法:


方法1:遍历关键词逐个替换

直接循环关键词数组,对字符串依次执行替换,每次替换后更新字符串即可:

function correctString(string, keywords) {
  let result = string;
  // 遍历所有关键词
  for (const keyword of keywords) {
    // 用replaceAll替换所有匹配的关键词(ES2021及以上版本支持)
    result = result.replaceAll(keyword, "");
  }
  return result;
}

console.log(correctString("If stringnot includes whelloords in array, remove them JavaScript", ["not", "hello"]));
// 输出:If string includes words in array, remove them JavaScript

如果需要兼容旧环境,replaceAll可以换成带全局标志的正则写法:

result = result.replace(new RegExp(keyword, 'g'), "");

方法2:正则表达式一次性替换

把关键词数组拼接成正则表达式,通过全局匹配一次性替换所有关键词,效率更高:

function correctString(string, keywords) {
  // 转义关键词中的正则特殊字符(比如. * +等),避免匹配出错
  const escapedKeywords = keywords.map(keyword => keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  // 拼接成正则,用|分隔表示匹配任意一个关键词,g表示全局匹配
  const regex = new RegExp(escapedKeywords.join('|'), 'g');
  return string.replace(regex, "");
}

console.log(correctString("If stringnot includes whelloords in array, remove them JavaScript", ["not", "hello"]));
// 输出:If string includes words in array, remove them JavaScript

这种方法只需要执行一次替换操作,适合关键词较多的场景,同时处理了关键词含特殊字符的情况。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:55:17