Skip to content
Advertisement

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 ***:

JavaScript

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?

Advertisement

Answer

Have you considered using RegExp?

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement