Java replaceAll - How to replace all blank characters in a String

By Alvin Alexander. Last updated: Jun 10, 2014

Today I needed a Java method to remove all the blank characters from a String. I started to write some code with a StringBuffer or a StringBuilder, then thought there must be some other way to do this. It's not that the StringBuilder/StringBuffer approach is hard, but just that someone must have already solved this problem.

That's when I thought of the replaceAll method of the String class, and that I might be able to use it. Sure enough, the following line of code returns a new String with all the blank characters removed:

String newName = oldName.replaceAll(" ", "");

Note that there is a blank space between the first set of double quotes in that line, and there is no space between the second set of quotes.

A note on using a regex

Because the first String the replaceAll method takes is really a regex, you can probably remove much more complicated string patterns using this technique, but I don't have that need currently, so I didn't try it. Off the top of my head, and not even typing this following code into a compiler, this next piece of Java source code should return a new String with all whitespace characters removed:

String newName = oldName.replaceAll("\\s", "");

Again, that code hasn't been tested or even typed into a Java IDE, so user beware.