从字符串中删除数组中出现的所有字符

时间:2017-10-26 15:49:33

标签: javascript string replace

我正在构建一个应用程序,需要从他们的输入中删除相当数量的文本,我想移动"删除"列入数组以便于管理。

const badWords = ['jamie', 'hutber'];
const naughtyString = 'Jamie Hutber everybody likes Jamie Chocolate';

期望输出将是:

'everybody likes Chocolate'

因此,如果不清楚,我想从字符串淘气中删除所有出现在badWords中的事件...

5 个答案:

答案 0 :(得分:1)

您在正确的路径上,将您的句子拆分为数组,删除所有出现的内容:

let goodSentence = naughtyString.split(' ').filter(s => badWords.indexOf(s.toLowerCase()) === -1).join(' ');

答案 1 :(得分:1)

如果它专门用于badWords,你可以这样:

var result = naughtyString;
badWords.forEach(function(badWord){
     result = result.split(new RegExp(badWord,'i')).join(Array(badWord.length).join("*"));
});
  

结果==“**** *****每个人都喜欢****巧克力”

答案 2 :(得分:0)

badWords上的单次迭代:

const badWords = ['jamie', 'hutber'];
let naughtyString = 'Jamie Hutber everybody likes Jamie Chocolate';

badWords.forEach(bad => {
    	
  let rgx = new RegExp(bad, 'ig');
  naughtyString = naughtyString.replace(rgx, '');

});

console.log(naughtyString);

答案 3 :(得分:0)

我提出了另一个更具可读性的想法:

const badWords = ['jamie', 'hutber'];
let naughtyString = 'Jamie Hutber everybody likes Jamie Chocolate';

const rgx = new RegExp(badWords.join('|'), 'gi');

let cleanString = naughtyString.replace(rgx, '');

console.log(cleanString);

答案 4 :(得分:-1)

你还需要检查,大小写..因为你的坏词都是小写的,但你的搜索字符串是大小写混合。

const badWords = ['jamie', 'hutber'];
const naughtyString = 'Jamie Hutber everybody likes Jamie Chocolate';

// 'everybody likes Chocolate'

function notBadWord(f) {
  return !badWords.includes(f.toLowerCase());
}

var out = naughtyString.split(/\s/).filter(notBadWord).join(" ");

console.log(out);