通过使用字符串数组替换字符串中的出现

时间:2019-04-05 21:56:10

标签: javascript arrays string replace

我有以下内容:

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

一种选择是构造一个正则表达式,在要替换的每个单词之间交替,然后在.map内,用空字符串替换这些单词的所有实例:

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 pattern = new RegExp(replaceMents.join('|'), 'g');

const newArr = arr.map(({ id, title }) => ({ id, title: title.replace(pattern, '').trim() }));
console.log(newArr);

如果替换项在正则表达式中可能包含具有特殊含义的字符(例如.$等),那么您需要在加入之前对它们进行转义:

const escapeRegex = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

new RegExp(replaceMents.map(escapeRegex).join('|'), 'g')

Is there a RegExp.escape function in Javascript?