If I have a given string, using JavaScript, is it possible to remove certain characters from them based on the ASCII code and return the remaining string e.g. remove all chars with ASCII code < 22 from the string?
As it turns out there are a lot of different solutions, here is a short overview (sorted from the fastest to the slowest)
let finalString = "";
for(let i = 0; i < myString.length; i++ ) {
if(myString.charCodeAt(i) < 22) continue;
finalString += myString.charAt(i);
}
Speed (for the benchmark bellow): 82,600 ops/s ±1.81%
const newStringArray = myString.split("").filter(e => e.charCodeAt(0) > 22)
let finalString = ""
for(let i = 0; i < newStringArray.length; i++ ) {
finalString += newStringArray[i]
}
Speed (for the benchmark bellow): 55,199 ops/s ±0.53%
33.17% slower
.joinconst newString = myString.split("").filter(e => e.charCodeAt(0) >= 22).join("");
Speed (for the benchmark bellow): 18,745 ops/s ±0.28%
77.31% slower
.reduceconst newString = myString.split("")
.filter(e => e.charCodeAt(0) > 22)
.reduce( (acc, current) => acc += current, "");
Speed (for the benchmark bellow): 17,781 ops/s ±0.23%
78.47% slower
The benchmark could be found here: https://jsbench.me/50k8zwue1p

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