r/learnjavascript • • Jan 11 '23

Ways to remove spaces from a string using JavaScript

Post image
205 Upvotes

33 comments sorted by

47

u/ashkanahmadi Jan 11 '23

Thanks for sharing. I just did a performance test.

The average time it takes each function (10,000 runs) to remove the spaces from a text with 1800 words/spaces in it.

  • replaceAll: 0.08585000002384185 miliseconds

  • replace: 0.10449000005722046 miliseconds

  • splitAndJoin: 0.2322219943579563 miliseconds

  • filterAndJoin: 1.1504000001549721 miliseconds

Seems like replaceAll is the fastest and filterAndJoin is the slowest.

15

u/capeladev Jan 11 '23

Wow that’s really awesome! I feel that there’s still a lot of people that are not familiar with the replaceAll() method as it was only introduced to ecma 2021, but it actually pays off in terms of performance!

1

u/revanyo Jan 12 '23

I totally figured the replaceAll() would be the slowest because it appears to be the easiest to use

3

u/woodentaint Jan 12 '23

Came into the comments looking for the answer to which is fastest. Thanks for posting this!

1

u/f_dg_ Aug 14 '25

Question. How do you measure the performance of each method? I'm just curious. thank you

1

u/ashkanahmadi Aug 14 '25

Had to go through my old codepens trying to find it haha. Here it is: https://codepen.io/AshkanAhmadi/pen/YzjVrvv?editors=0010 Make sure you check out the Console

1

u/f_dg_ Aug 25 '25

Ohhhh I see there's an interface for that. Thanks for this!

28

u/kap89 Jan 11 '23

If you want to remove all whitespace, not only spaces:

text.replace(/\s/g, '')

3

u/capeladev Jan 11 '23

That will also remove tabs, new lines and carriage returns, right?

7

u/kap89 Jan 11 '23

Yes.

Matches a single white space character, including space, tab, form feed, line feed, and other Unicode spaces. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

Source: MDN

2

u/Crazy_Falcon_2643 Jan 12 '23

Yeah, I don’t understand this lol

0

u/[deleted] Jan 12 '23

[deleted]

2

u/acquiescentLabrador Jan 11 '23

Which is the most efficient, performance wise?

10

u/Bloodsucker_ Jan 11 '23

First one.

The two at the bottom must be a troll example or something because wtf. Is this post a joke?

3

u/capeladev Jan 11 '23

The last 2 are for educational purposes, they work but we should prefer one of the other methods for this type of operation

1

u/Pokimeme Jan 12 '23

Yeah I didn't know you could spread a string like tht

3

u/kap89 Jan 11 '23 edited Jan 11 '23

Benchmark for V8 (Chrome, Edge, Opera, Node), run on Node 18:

Running "Remove spaces (50 characters string)" suite...
Progress: 100%

  replaceAll:
    902 907 ops/s, ±1.30%   | fastest

  replace:
    811 102 ops/s, ±0.42%   | 10.17% slower

  split-join:
    519 097 ops/s, ±1.99%   | slowest, 42.51% slower

  spread-filter-join:
    624 614 ops/s, ±0.41%   | 30.82% slower

Finished 4 cases!
  Fastest: replaceAll
  Slowest: split-join


Running "Remove spaces (1000 characters string)" suite...
Progress: 100%

  replaceAll:
    61 346 ops/s, ±0.58%   | fastest

  replace:
    49 594 ops/s, ±0.34%   | 19.16% slower

  split-join:
    37 432 ops/s, ±0.31%   | 38.98% slower

  spread-filter-join:
    36 239 ops/s, ±0.41%   | slowest, 40.93% slower

Finished 4 cases!
  Fastest: replaceAll
  Slowest: spread-filter-join

Code:

export function removeSpaces(text) {
  return text.replaceAll(" ", "");
}

export function removeSpaces2(text) {
  return text.replace(/ /g, "");
}

export function removeSpaces3(text) {
  return text.split(" ").join();
}

export function removeSpaces4(text) {
  return [...text].filter((char) => char !== " ").join("");
}

Benchmark code: Gist

1

u/capeladev Jan 11 '23

That will depend on the JS engine that is running the code, but generally the most performant one is replaceAll()

5

u/Electronic_Ad9248 Jan 12 '23

As a beginner in JS, I learned so much from this post and the comments. Thank you all.

1

u/Ronin-s_Spirit Jan 11 '23

What about the map?

1

u/capeladev Jan 11 '23

That would be similar to the last one just replacing the filter to a map and returning an empty string if the char is a space, but I think that would make it even less efficient that what it already is 😂

1

u/capeladev Jan 11 '23

Hummmm, actually you may be right, maybe it would be a little faster to map than to filter

2

u/[deleted] Jan 12 '23

Which is easier for people to read: method calls on the same line or below like this?

I’ve seen this style and I’m only lukewarm on it.

1

u/alexbarrett Jan 12 '23

It's the standard way to wrap lines when they exceed your max line length. It's been used here because the image is divided into quarters, resulting in a very short line length. For real code your max line length will be between 80–120 so you would keep it on one line.

1

u/[deleted] Jan 12 '23

What I mean is: I’ve seen this style applied regardless of line length - religiously. So I was curious :)

For wrapping: I agree it’s the way to go.

1

u/MarionberrySad7677 Feb 14 '25

Thanks, I needed the replaceAll function for my project, and this worked out great. Now, where there were long white spaces (6 tabs in total), there is now a clean neat code.
I use it to format my SQL Server SQL Script to ready it for our website.

This is how I was able to use it.

function removeSpaces(text) {
s = document.getElementById("output").value;
s = s.replaceAll(' ','');
document.getElementById("output").value = s;
return text
}

Here is the site. https://www.cffcs.com/Stuff/SQL.asp

Keep in mind, this will take your script that is line and long space separated and make it into ONE fluid line to be placed in a SQL Script for database work.

Thanks, capeladev

You rock my friend.
Wayne

1

u/RepresentativeDog380 Jan 12 '23

Could someone tell me the font used in the code?

1

u/TheRNGuy Jan 18 '23

There's also unbreakable space ( ) so regex is best.

Why would anyone use 3 and 4.

0

u/HunterSup Jan 12 '23

string.trim()

-1

u/Comprehensive_Step72 Jan 12 '23

If you are going to use an iterator, you should be using reduce:

let stripped = [...str].reduce((acc, letter) => letter !== ' ' ? acc + letter : acc, '') ;