1

My code is as follows:

array.forEach(el => {
  string = string.replace(el, `censored`);
});

array : my array of words that I want to censor. string : the string that the words need censoring.

My issue is that this process is quite slow and also if the word in my string is written using capitals, it's getting missed. Any ideas how should I solve this issue? Thank you.

Sponge Bob
  • 13
  • 3

1 Answers1

1

maybe you can use regex

let array = ['mate']
let string = 'Hello Mate, how are you mate?'

let re = new RegExp(array.join("|"),"gi");
let str = string.replace(re, 'censored');

output:

"Hello censored, how are you censored?"
AlexZvl
  • 2,092
  • 4
  • 18
  • 32
  • 1
    Amazing! Thank you so much, that works like a treat. – Sponge Bob Dec 13 '20 at 17:08
  • Glad it worked! consider marking it as a correct answer :) – AlexZvl Dec 13 '20 at 17:09
  • this is a good solution but the blocked list is likely to grow. If it were 10000 words would this solution be efficient? – trk Dec 13 '20 at 17:16
  • 1
    I am not planning to have 10000 words that need censoring...at least not for now. If there is another solution, please post it. I am open for other solutions as well. – Sponge Bob Dec 13 '20 at 17:20