Question
Given the Java string:
String mysz = "name=john age=13 year=2001";
How can you remove the whitespace throughout the string to produce the following result while preserving the = characters?
String mysz2 = "name=johnage=13year=2001";
trim() only removes whitespace at the beginning and end of the entire string. Using replaceAll("\\W", "") also removes the = characters, which should remain.
Short Answer
You will learn the difference between trimming edge whitespace and replacing whitespace anywhere in a Java string. You will also see why \W removes more than spaces and how to choose the correct regular expression.
Concept
String.trim() and regular-expression replacement solve different problems.
trim()removes leading and trailing whitespace only.replaceAll()searches the entire string using a regular expression.\sis a regular-expression character class that matches whitespace, including spaces, tabs, and line breaks.\Wmeans a non-word character. It matches spaces, but it also matches punctuation such as=, so it is too broad for this task.
To remove whitespace anywhere while keeping all non-whitespace characters, use:
String result = mysz.replaceAll("\\s+", "");
The + means “one or more whitespace characters.” Grouping consecutive whitespace into one match is usually slightly clearer and more efficient than replacing one character at a time.
This matters in real programs because text input may contain extra spaces, tabs, or newlines. Removing only the characters you intend to remove prevents accidental changes to meaningful data.
Mental Model
Think of a string as a sentence written on a strip of paper.
trim()cuts off blank paper at the left and right ends only.replaceAll("\\s+", "")scans the entire strip and erases every run of blank space.replaceAll("\\W", "")erases anything that is not a letter, digit, or underscore. That is like using an overly powerful eraser: it removes blanks, but it also removes useful symbols such as=.
Syntax and Examples
Use replaceAll() when you want to replace text matched by a regular expression.
String mysz = "name=john age=13 year=2001";
String mysz2 = mysz.replaceAll("\\s+", "");
System.out.println(mysz2);
// name=johnage=13year=2001
Java string literals treat \ as an escape character. Therefore, the regular expression \s+ must be written as "\\s+" in Java source code.
What each part means
| Part | Meaning |
|---|---|
replaceAll(...) | Replaces every match in the string |
"\\s+" | Matches one or more whitespace characters |
"" | Replaces each match with nothing |
Step by Step Execution
Consider this code:
String input = "name=john age=13\tyear=2001";
String output = input.replaceAll("\\s+", "");
Step by step:
inputcontains two spaces betweenjohnandage, plus a tab between13andyear.replaceAll("\\s+", "")searches from the beginning of the string.- It finds the two consecutive spaces.
\s+treats them as one match and replaces them with an empty string. - It later finds the tab character. A tab is also whitespace, so it is replaced with an empty string.
- Letters, digits, and
=do not match\s+, so they remain unchanged. outputbecomes:
name=johnage=13year=2001
Strings are immutable in Java. replaceAll() returns a new string; it does not change itself.
Real World Use Cases
Whitespace removal is useful when the whitespace is formatting rather than meaningful content.
- Normalizing identifiers: Remove accidental spaces from a product code such as
"AB 123". - Cleaning imported data: Remove tabs and line breaks from a compact token received from a file.
- Processing user-entered configuration: Normalize values when your format explicitly does not allow spaces.
- Preparing machine-readable tokens: Clean a string before validating it against a strict format.
Be careful with names, addresses, sentences, and natural-language text. Removing all whitespace from "John Smith" produces "JohnSmith", which usually changes its meaning. In those cases, normalize repeated whitespace to one space instead:
String normalized = input.trim().replaceAll("\\s+", " ");
Real Codebase Usage
In production code, developers usually make the cleanup rule explicit and choose it based on the data format.
Remove all whitespace from a compact token
String compact = rawInput.replaceAll("\\s+", "");
Normalize human-readable text
String normalizedName = rawName.trim().replaceAll("\\s+", " ");
Validate before processing
A guard clause makes invalid input clear:
static String removeWhitespace(String input) {
if (input == null) {
throw new IllegalArgumentException("input must not be null");
}
return input.replaceAll("\\s+", "");
}
Preserve structured data when possible
For data like name=john age=13, removing spaces creates a hard-to-read string and can make later parsing ambiguous. If you need the individual fields, parse the format into key-value pairs rather than permanently deleting separators. For example, split fields on whitespace first, then split each field on .
Common Mistakes
Using trim() to remove internal spaces
String result = " a b ".trim();
// result is "a b", not "ab"
trim() affects only the beginning and end. Use replaceAll("\\s+", "") for whitespace throughout the string.
Using \W when you mean whitespace
String result = "name=john age=13".replaceAll("\\W", "");
// namejohnage13
\W removes = because = is not a word character. Use \s+ to target whitespace only.
Forgetting to escape the backslash in Java source
String result = input.replaceAll("\s+", );
Comparisons
| Approach | What it removes | Best use |
|---|---|---|
trim() | Whitespace at the start and end | Clean surrounding input whitespace |
strip() | Unicode-aware leading and trailing whitespace | Modern Java edge cleanup |
replace(" ", "") | Literal space characters only | Input guaranteed to contain normal spaces |
replaceAll("\\s+", "") | Whitespace anywhere, including tabs and line breaks | Remove all common whitespace |
replaceAll("\\s+", " ") | Repeated whitespace becomes one space | Normalize readable text |
replaceAll("\\W", "") | Everything except letters, digits, and |
Cheat Sheet
// Remove all whitespace: spaces, tabs, and line breaks
String compact = input.replaceAll("\\s+", "");
// Remove normal spaces only
String compactSpaces = input.replace(" ", "");
// Remove whitespace only at both ends
String edgesRemoved = input.trim();
// Java 11+: Unicode-aware removal at both ends
String edgesRemovedUnicode = input.strip();
// Keep words readable: trim ends and collapse internal whitespace
String normalized = input.trim().replaceAll("\\s+", " ");
Rules:
- Use
"\\s+", not"\\W", to match whitespace. - Save the returned value because Java strings cannot be modified in place.
- Use
replace()for literal text andreplaceAll()for regular expressions. - Remove all whitespace only when spaces are not meaningful data.
FAQ
How do I remove all spaces from a Java string?
For normal space characters only, use:
String result = input.replace(" ", "");
For all common whitespace, including tabs and newlines, use input.replaceAll("\\s+", "").
Why does trim() not remove spaces in the middle?
trim() is designed to remove whitespace only from the beginning and end of a string. It does not inspect internal whitespace.
Why does replaceAll("\\W", "") remove equals signs?
\W means “non-word character,” not “whitespace.” An equals sign is a non-word character, so it matches and is removed.
What does \s+ mean in Java regex?
\s matches whitespace. + means one or more occurrences. In a Java string literal, write it as "\\s+" because the backslash must be escaped.
Does replaceAll() change the original string?
No. Java strings are immutable. returns a new string that you must assign to a variable.
Mini Project
Description
Build a small Java utility that cleans a compact configuration-style string. It removes whitespace without removing the = separators, then prints the original and cleaned values.
Goal
Create a program that removes spaces, tabs, and line breaks from a string while preserving all other characters.
Requirements
Requirement 1
Keep learning
Related questions
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.