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:
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:
You can replace the empty string with any text. For example, if you use '#', you will see the difference:
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:
split() and join()
The split() and join() methods can also be used to delete the space from the given string:
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.).