Recently, i wrote some code for filtering bad words in a string. And a tons of words are going to be filtered. My code works but the performance is not really well as expected.
Below code is only the demo:
Method 1:
let list = [ "omg", "bbq", "wth", "hello", "world" ];
let smallString = "wthhello123456worldomg789bbqomgomg";
for (let i = 0; i < list.length; i++) {
smallString = smallString.replace(new RegExp(list[i], "g"), "***");
}
Method 2:
let list = [ "omg", "bbq", "wth", "hello", "world" ];
let smallString = "wthhello123456worldomg789bbqomgomg";
for (let i = 0; i < list.length; i++) {
smallString = smallString.split(list[i]).join("***");
}
I had also make the performance test with jsperf which comparing with split & join or replace : https://jsperf.com/split-join-vs-replace-dicky
The test result shows that split & join is faster than replace when replacing a small string. But it will be slow when replacing a large string. (I noted that the result will be changed sometimes)
What i really want
I actually needs a stable function to replacing the word with better performance. Any advices ? It can be another method that without using replace or split & join. Thanks a lot
Use a single regex to replace all targets in one call:
smallString = smallString.replace(/omg|bbq|wth|hello|world/g, "***");
If you have to keep the targets as an array, turn it into a regex on the fly:
smallString = smallString.replace(new RegExp(list.join("|"), "g"), "***");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With