How to Remove or Replace All Whitespace from a String in JavaScript
Removing or replacing whitespace is a fundamental string manipulation task, essential for data sanitization, formatting, and preparing strings for comparison. A common requirement is to remove all whitespace characters (including spaces, tabs, and newlines) or to replace them with a different character.
This guide will demonstrate the modern and most effective methods for this task using String.prototype.replace() with a regular expression and the newer String.prototype.replaceAll().
The Core Task: Removing All Whitespace vs. Only Spaces
It's important to distinguish between two common goals:
- Removing All Whitespace: This means removing every space, tab (
\t), newline (\n), and any other whitespace character. - Removing Only Space Characters: This means removing only the standard space character (
) while leaving tabs and newlines intact.
The best method depends on which of these you need to do.
Removing All Whitespace (Spaces, Tabs, Newlines)
For this task, a regular expression is the most powerful and reliable tool.
Problem: you have a string with a mix of different whitespace characters that you want to remove completely.
// Problem: Remove all spaces, tabs, and newlines from this string.
const messyString = ' Hello\tWorld\n This is a test. ';
Solution: use String.prototype.replace() with the /\s/g regular expression.
function removeAllWhitespace(str) {
// The regex /\s/g finds all whitespace characters globally.
return str.replace(/\s/g, '');
}
// Example Usage:
const messyString = ' Hello\tWorld\n This is a test. ';
const cleanString = removeAllWhitespace(messyString);
console.log(cleanString); // Output: 'HelloWorldThisisatest.'
This is the recommended best practice for removing all types of whitespace.
Removing or Replacing Only Space Characters
If your goal is to target only the standard space character, the modern String.prototype.replaceAll() method is the most readable and direct solution.
Problem: you want to replace all spaces with a different character (like a hyphen), but leave other whitespace like newlines alone.
// Problem: Replace only the spaces with hyphens.
const sentence = 'This is a sentence.\nAnd another line.';
Solution: use replaceAll() with a simple string argument.
const sentence = 'This is a sentence.\nAnd another line.';
// Replace every space character with a hyphen.
const hyphenated = sentence.replaceAll(' ', '-');
console.log(hyphenated);
// Output: 'This-is-a-sentence.\nAnd-another-line.'
// To remove the spaces instead, just replace with an empty string.
const noSpaces = sentence.replaceAll(' ', '');
console.log(noSpaces); // Output: 'Thisisasentence.\nAndanotherline.'
This is the recommended best practice when you only need to target the space character.
How the Regular Expression Works
The regular expression /\s/g is the key to removing all whitespace.
/ ... /: The delimiters that mark the beginning and end of the regular expression.\s: A special "metacharacter" that matches any whitespace character. This includes the space, tab, newline, carriage return, and others.g: This is the global flag. It is crucial. It tells thereplace()method to replace all matches it finds, not just the first one.
So, /\s/g translates to: "Find every whitespace character, wherever it appears in the string." The replace() method then replaces these matches with an empty string, effectively deleting them.
Conclusion
Removing or replacing whitespace is a simple task with clear, modern solutions in JavaScript.
- To remove all types of whitespace (spaces, tabs, newlines, etc.), the recommended best practice is to use
replace()with a global regular expression:str.replace(/\s/g, ''). - To remove or replace only the space character, the most readable and modern method is
str.replaceAll(' ', '').