JavaScript如何查找包含指定子串的数组元素并完成替换?
实现方案
你遇到的问题核心是indexOf仅支持完全匹配,要实现模糊匹配查找对应元素,使用数组的findIndex、map等支持自定义判断逻辑的方法即可实现需求。
1. 仅替换第一个匹配到的包含关键词的元素
如果只需要修改第一个出现关键词的数组项,使用findIndex查找对应下标即可,逻辑和你原来的写法对齐:
const array = ['test blabla', 'haha hihi', 'test 123'] const targetKeyword = 'test' const replaceValue = 'newblabla' // 查找第一个包含关键词的元素下标 const index = array.findIndex(item => item.includes(targetKeyword)) if (index !== -1) { array[index] = replaceValue } console.log(array) // 输出结果:['newblabla', 'haha hihi', 'test 123']
如果需要兼容ES5及更早的运行环境,可以把
item.includes(targetKeyword)替换为item.indexOf(targetKeyword) !== -1,效果完全一致。
2. 替换所有包含关键词的元素
如果需要把数组中所有包含关键词的项全部替换,推荐使用map方法生成新数组,避免直接修改原数组产生副作用:
const array = ['test blabla', 'haha hihi', 'test 123'] const targetKeyword = 'test' const replaceValue = 'newblabla' // 生成新数组(不修改原数组,推荐写法) const newArray = array.map(item => { return item.includes(targetKeyword) ? replaceValue : item }) console.log(newArray) // 输出结果:['newblabla', 'haha hihi', 'newblabla'] // 直接修改原数组的写法(按需选择) array.forEach((item, index) => { if (item.includes(targetKeyword)) { array[index] = replaceValue } })
扩展说明
如果需要实现大小写不敏感的匹配(比如同时匹配Test、TEST等),把判断逻辑修改为以下形式即可:
item.toLowerCase().includes(targetKeyword.toLowerCase())
内容的提问来源于stack exchange,提问作者PierreB
相关产品推荐
相关产品推荐

