How to Remove All Spaces from a String in JavaScript

Last updated on June 20, 2022
How to Remove All Spaces from a String in JavaScript

1. String replaceAll() Method

To remove all spaces from a string in JavaScript, call the replaceAll() method on the string, passing a string containing a space as the first argument and an empty string ('') as the second. For example, str.replaceAll(' ', '') removes all the spaces from str.

const str = 'A B C';
const allSpacesRemoved = str.replaceAll(' ', '');

console.log(allSpacesRemoved); // ABC

The String replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The first argument is the pattern to match, and the second argument is the replacement. So, passing the empty string as the second argument replaces all the spaces with nothing, which removes them.

2. String replace() Method with Regex

Alternatively, we can remove all spaces from a string by calling the replace() method on the string, passing a regular expression matching any space as the first argument, and an empty string ('') as the second.

const str = 'A B C';
const allSpacesRemoved = str.replace(/ /g, '');

console.log(allSpacesRemoved); // ABC

We use the g regex flag to specify that all spaces in the string should be matched. Without this flag, only the first space will be matched and replaced:

const str = 'A B C';

// No 'g' flag in regex
const spacesRemoved = str.replace(/ /, '');

// Only first space removed
console.log(spacesRemoved); // AB C

The String replace() method returns a new string with all the matches replaced with the second argument passed to it. We pass an empty string as the second argument to replace all the spaces with nothing, which removes them.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also