Scala: Removing Whitespace

Often times, your strings will have white spaces that need to be removed. This page will help you achieve that goal in  Scala. There are two kinds of white spaces that you usually require removal. They are trailing and leading white spaces. Let us see a few examples

Since Scala uses Java's String class, the documentation for all of the below mentioned methods is available at http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

First, the easy part. Removing both trailing and leading whitespaces.

Scala provides #trim method in its string class which helps to remove both leading and trailing white spaces.

var a = "    hello world   ".trim // must produce "hello world"



Removing Trailing White Spaces: Scala doesn't have an inbuilt method in the String class for removing trailing white spaces. So we seek the help of Regular Expressions. The regular expression """(?m)\s+$""" matches the trailing white spaces in a string. With the help of this regular expression and #replaceAll method of the String class, we can replace all the white spaces with empty ("") characters.

var a = "hello world    ".replaceAll("""(?m)\s+$""","") // must produce "hello world"



Removing Leading White Spaces: Scala doesn't have an inbuilt method in the String class for removing leading white spaces. So we seek the help of Regular Expressions. The regular expression """^\s+(?m)""" matches the trailing white spaces in a string. With the help of this regular expression and #replaceAll method of the String class, we can replace all the white spaces with empty ("") characters.

var a = "    hello world".replaceAll("""^\s+(?m)""","") // must produce "hello world"