How to Remove Whitespace from String in Java
The Challenge
Remove spaces, tabs, and newlines from a string!
Solutions
Method 1: Remove All Whitespace
String text = " Hello World ";
String result = text.replaceAll("\\s+", "");
System.out.println("'" + result + "'");
// Output: 'HelloWorld'Method 2: Remove Leading/Trailing Whitespace
String text = " Hello World ";
String result = text.trim();
System.out.println("'" + result + "'");
// Output: 'Hello World'Method 3: Replace Multiple Spaces with Single Space
String text = "Hello World";
String result = text.replaceAll("\\s+", " ");
System.out.println("'" + result + "'");
// Output: 'Hello World'Method 4: Using Java 11+ strip()
String text = " Hello World ";
String result = text.strip(); // Better than trim() for Unicode
System.out.println("'" + result + "'");
// Output: 'Hello World'Did You Know?
Java 11+ introduced strip(), stripLeading(), and stripTrailing() which handle Unicode whitespace better than trim()!
Pro Tip
The regex \\s matches any whitespace character (space, tab, newline, carriage return). Use \\s+ to match one or more whitespace characters.
Real-World Use Cases
- Data cleaning: Normalize user input
- Form validation: Clean up submitted data
- Text processing: Remove formatting
- File parsing: Clean CSV/text files
›Short versionOpen if you only have a minute.
- trim and strip remove only the ends. Internal spaces stay.
- strip is Unicode-aware. trim removes code points at or below U+0020.
- replace(" ", "") leaves tabs and newlines.
- replaceAll("\\s+", "") removes every whitespace run, including the ones inside a name.
Remove whitespace
Remove spaces, tabs, and newlines when the result should be compact text.
Working approach
- Use trim or strip when only the ends are unwanted.
- Use replaceAll("\\s+", "") when every whitespace character should go.
- Use replaceAll("\\s+", " ") after trim when the goal is to collapse runs, not delete them.
Walk the sample
- Input " a b"
- A pattern of whitespace runs matches the spaces
- Replacing those runs with nothing leaves "ab"
The trap
trim looks like "remove whitespace" and does not touch the middle. A tab between two letters survives.
String endsOnly = " a\tb ".trim(); // "a\tb"
String compact = " a\tb ".replaceAll("\\s+", ""); // "ab"
String collapsed = "a b".trim().replaceAll("\\s+", " "); // "a b"What does "a\tb".trim() return?
"a\tb". The tab is not at either end, and trim never looks at internal characters.
replace(" ", "") also leaves the tab, because a tab is not the space character. \\s matches both.
Time O(n), space O(n) for the new string.
Easy to get wrong
- Calling trim and expecting internal spaces to disappear.
- Forgetting that the replacement argument of replaceAll is a regex.