W3docs

How to Remove Spaces From String

Read this JavaScript tutorial and learn several methods that are used to remove spaces from a string. Also, know which is the fastest method to choose.

In today’s tutorial, we will show you simple solutions for removing spaces from a string and explain each step.

replace()

If you want to remove all the space in the string, you can use the replace() method:

javascript— editable

Here <kbd class="highlighted">\s</kbd> is the regex for whitespace, and <kbd class="highlighted">g</kbd> is the global flag, which matches all occurrences. The + quantifier ensures each contiguous string of spaces is replaced with the empty string.

You can also use another version:

javascript— editable

You can replace the empty string with any text. For example, if you use '#', you will see the difference:

javascript— editable
Info

Note: /\\s+/g is typically faster for strings with consecutive spaces, while /\\s/g processes each space individually.

For modern browsers, you can also use replaceAll() for literal space removal without regex:

javascript— editable

split() and join()

The split() and join() methods can also be used to delete the space from the given string:

javascript— editable

You can use either method, but consider the following:

  • Use split(' ').join('') for simple space removal.
  • Use replace(/\s+/g, '') when handling various whitespace characters (tabs, newlines, etc.).