copenndthagen
copenndthagen

Reputation: 50742

Remove characters from a string based on ascii code in 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?

Upvotes: 4

Views: 799

Answers (4)

WolverinDEV
WolverinDEV

Reputation: 1524

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

Upvotes: 7

Radu Diță
Radu Diță

Reputation: 14171

Concatenating may be faster than join for large strings.

So building on @WolveringDEV answers you can loop over the array and concatenate instead of join

const newStringArray =  myString.split("")
 .filter(e => e.charCodeAt(0) > 22)

let finalString = ""

for(let i = 0; i < newStringArray.length; i++ ) {
   finalString += newStringArray[i]
}

Upvotes: 0

Rajat Verma
Rajat Verma

Reputation: 307

Yeah, it is possible using the str.charCodeAt() method of javascript. You can convert the given string into an array of characters and then use the map method to compare each character with the ASCII code with which you want to compare your string characters with.
This will return a new array that follows the condition and then you can just join that array to form a string again.

Upvotes: 0

Tom Truyen
Tom Truyen

Reputation: 363

You could loop through the string and for each letter use charCodeAt(letter) that way you know its ASCII code and then you can perform your if statement.

Upvotes: 0

Related Questions