How to Remove All Spaces from a String in JavaScript

Every Crazy Thing JavaScript Does

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.
Every Crazy Thing JavaScript Does

See also
- How to Remove All Vowels From a String in JavaScript
- How to Remove All Whitespace from a String in JavaScript
- How to Remove a Class From All Elements in JavaScript
- How to Remove Special Characters From a String in JavaScript
- How to Convert an Array to a String with Spaces in JavaScript
- How to Add a Class to All Elements With JavaScript