javascript - 使用字符串数组替换字符串中的出现
问题描述
我有以下内容:
var arr = [{id: 0, title: 'This is a test Hello World Hello'}, {id: 1, title: 'I like the World'}, {id: 2, title: 'The Sun is bright'}, {id: 3, title: 'Cat'}],
replaceMents = ['Hello', 'World'];
我想在替换后有这样的数组:
[{
id: 0,
title: 'This is a test'
}, {
id: 1,
title: 'I like the'
}, {
id: 2,
title: 'The Sun is bright'
}, {
id: 3,
title: 'Cat'
}]
因为我不想使用经典的 arr.forEach,所以我正在寻找更好的解决方案。
有哪些可能性?
我想像
var newArr = arr.map(el => replaceMents.forEach(rep => el.title.replace(rep, '')))
解决方案
不使用正则表达式的另一种选择,然后可能需要另一个正则表达式来转义特殊字符。您是否可以拆分过滤器连接。
const arr = [{id: 0, title: 'This is a test Hello World Hello'}, {id: 1, title: 'I like the World'}, {id: 2, title: 'The Sun is bright'}, {id: 3, title: 'Cat'}]
const replaceMents = ['Hello', 'World'];
const newArr = arr.map(({ id, title }) => (
{ id, title:
title.split(' ').
filter(f => !replaceMents.includes(f)).
join(' ')
}));
console.log(newArr);
推荐阅读
- flutter - 如何将焦点转移到 Flutter 中的下一个 TextField?
- javascript - 重复的字符串值需要分开
- c# - Windows 服务器无法在 .net 框架 4.5.1 上运行
- java - Java 自动向量化
- java - 使用 Logback 的 RollingFileAppender 时,有没有办法使用默认的 Springboot“/actuator/logfile”端点?
- asp.net-mvc - 获取 ASP.Net MVC 项目中的分支名称
- python - 修改django查询集的结果
- c# - 用字符串生成器连接字符串?
- python - Apache Spark 读取 CSV 文件 - ClassNotFoundException
- javascript - 无序字符串数组与 lodash 的比较