首页 > 解决方案 > 使用字符串数组替换字符串中的出现

问题描述

我有以下内容:

 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, '')))

标签: javascriptarraysstringreplace

解决方案


不使用正则表达式的另一种选择,然后可能需要另一个正则表达式来转义特殊字符。您是否可以拆分过滤器连接。

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);


推荐阅读