Question

Remove Whitespace from a String in Java

javawhitespace

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.
  • \s is a regular-expression character class that matches whitespace, including spaces, tabs, and line breaks.
  • \W means 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 =.
Take Quiz

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

PartMeaning
replaceAll(...)Replaces every match in the string
"\\s+"Matches one or more whitespace characters
""Replaces each match with nothing

For ordinary single spaces only, replace() is simpler because it does not use regular expressions:

String result = mysz.replace(" ", "");

However, this does not remove tabs or line breaks. Prefer replaceAll("\\s+", "") when input can contain different kinds of whitespace.

Step by Step Execution

Consider this code:

String input = "name=john  age=13\tyear=2001";
String output = input.replaceAll("\\s+", "");

Step by step:

  1. input contains two spaces between john and age, plus a tab between 13 and year.
  2. replaceAll("\\s+", "") searches from the beginning of the string.
  3. It finds the two consecutive spaces. \s+ treats them as one match and replaces them with an empty string.
  4. It later finds the tab character. A tab is also whitespace, so it is replaced with an empty string.
  5. Letters, digits, and = do not match \s+, so they remain unchanged.
  6. output becomes:
name=johnage=13year=2001

Strings are immutable in Java. replaceAll() returns a new string; it does not change input 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+", " ");
Take Quiz

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+", "");

In modern Java, \s in a string literal represents a literal space escape, not the regex whitespace class. To pass regex \s+, write:

String result = input.replaceAll("\\s+", "");

Expecting the original variable to change

input.replaceAll("\\s+", "");
System.out.println(input); // Still unchanged

Assign the returned string:

input = input.replaceAll("\\s+", "");

Removing whitespace when it is meaningful

Do not remove all spaces from display text, passwords, addresses, or free-form messages unless your requirements explicitly say to do so.

Comparisons

ApproachWhat it removesBest use
trim()Whitespace at the start and endClean surrounding input whitespace
strip()Unicode-aware leading and trailing whitespaceModern Java edge cleanup
replace(" ", "")Literal space characters onlyInput guaranteed to contain normal spaces
replaceAll("\\s+", "")Whitespace anywhere, including tabs and line breaksRemove all common whitespace
replaceAll("\\s+", " ")Repeated whitespace becomes one spaceNormalize readable text
replaceAll("\\W", "")Everything except letters, digits, and _Build a word-character-only value, not whitespace removal

String.replace() performs literal replacement. String.replaceAll() treats its first argument as a regular expression. Choose replace() when regex matching is unnecessary.

Take Quiz

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 and replaceAll() 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. replaceAll() returns a new string that you must assign to a variable.

Should I use replace() or replaceAll()?

Use replace() for a literal character or substring, such as a regular space. Use replaceAll() when you need regex matching, such as all whitespace types.

How can I replace multiple spaces with one space instead of deleting them?

Use:

String result = input.trim().replaceAll("\\s+", " ");
Take Quiz

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

Take Quiz

Keep learning

Related questions

View more