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.
Note
Strings in JavaScript are immutable, and replaceAll()
returns a new string without modifying the original.
const str = 'A B C';
const allSpacesRemoved = str.replaceAll(' ', '');
console.log(allSpacesRemoved); // ABC
// Original not modified
console.log(str); // A B C
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.
Note
As with replaceAll()
, replace()
returns a new string without modifying the original.
const str = 'A B C';
const spacesRemoved = str.replace(/ /g, '');
console.log(spacesRemoved); // ABC
// Original not modified
console.log(str); // A B C
Tip
The regular expression we specified only matches spaces in the string. To match and remove all whitespace characters (spaces, tabs and newlines), we’ll have to use a different regex:
const str = 'A B C \t D \n E';
const whitespaceRemoved = str.replace(/\s/g, '');
console.log(whitespaceRemoved); // ABC
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.