Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove characters from a string based on ascii code in JavaScript

Tags:

javascript

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?

like image 786
copenndthagen Avatar asked Oct 21 '25 04:10

copenndthagen


1 Answers

As it turns out there are a lot of different solutions, here is a short overview (sorted from the fastest to the slowest)

A simple for loop

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%

For loop after splitting and filtering the string

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

One liner with .join

const newString = myString.split("").filter(e => e.charCodeAt(0) >= 22).join("");

Speed (for the benchmark bellow): 18,745 ops/s ±0.28%
77.31% slower

One liner with .reduce

const 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

Benchmark

The benchmark could be found here: https://jsbench.me/50k8zwue1p
https://jsbench.me/50k8zwue1p

like image 197
WolverinDEV Avatar answered Oct 23 '25 19:10

WolverinDEV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!