Skip to content

replaceAll in JavaScript for loop is too slow, looking for an alternative approach

I’m making a browser extension that replaces all profane words on a website with ***. Right now, I have a huge JS array with all the profane words (2k+ words).
I’m using a for loop to loop over each word in the profaneWords array and replace any instance of a matching word with ***:

    for (let i = 0; i < profaneWords.length; i++) {
      let element = profaneWords[i];
      document.body.innerHTML = document.body.innerHTML.replaceAll(
        element,
        "***"
      );
    }

With this, it takes about 5 minutes for my browser to search and replace all instances of all the profane words on a website, with ***. But, before it is done mapping over the words, no changes are made to the website. So for the 5 minutes, it looks like nothing is happening.

I tested this method with another array that was much smaller (10 words) and the replacing was almost instant.

Is there a better way I could go about implementing this for my array with over 2000 elements?

Answer

Have you considered using RegExp?

const str = 'Waiting on ass, asset , and tit titillation, ass.';
const profaneWords = ['ass', 'tit'];


const regex = new RegExp('\b'+profaneWords.join('\b|\b')+'\b', 'g');
var newstr =  str.replace(regex, '***');
console.log(newstr);