Blog

How to trim whitespace from a string in Go

The easiest way to trim whitespace from a string in Go (Golang) is to use one of the functions from the strings package in the Go standard library.

Contents

  1. Trim Left and Right Whitespace
  2. Trim Left Whitespace
  3. Trim Right Whitespace
  4. Trim Duplicate Whitespace
  5. Other Trim Functions

Trim Left and Right Whitespace in Go

Let's start by talking about how to trim both leading and trailing whitespace from a string. The strings package from the standard library has a function that does just this. It is the strings.TrimSpace() function. Whitespace characters are considered any of '\t', '\n', '\v', '\f', '\r', ' ' (the space character), 0x85, and 0xA0.

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := strings.TrimSpace(`
    Ice Cream 

`)
    fmt.Printf(">>%s<<", s)
}
>>Ice Cream<<

As you can see, we have removed the new lines, tabs, and white space from the beginning and end of the string. However, the space character between Ice and Cream has been preserved.

Trim Left Whitespace in Go

Unfortunately, the Go strings package does not have a strings.TrimLeftSpace() function. So, we will have to write it ourselves. However, the other trim functions in the strings package make this very easy. There are three functions in particular that help us write our own trim functions: strings.TrimFunc(), strings.TrimLeftFunc(), and strings.TrimRightFunc().

Each of these three functions is a higher-order function that takes a function func(rune) bool as their second argument. If that function returns true, the rune will be removed. This process will repeat for each appropriate side (left or right) until false is returned or the string is empty.

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func trimLeftSpace(s string) string {
    return strings.TrimLeftFunc(s, unicode.IsSpace))
}

func main() {
    s := trimLeftSpace(`
    Ice Cream 

`)
    fmt.Printf(">>%s<<", s)
}

>>Ice Cream 

<<

The results are exactly what we would expect. Our function has removed the new line and tab characters from the beginning of the string.

Trim Right Whitespace in Go

To remove whitespace on the right side of a string we can simply swap strings.TrimLeftFunc() in the previous example for strings.TrimRightFunc().

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func trimRightSpace(s string) string {
    return strings.TrimRightFunc(s, unicode.IsSpace))
}

func main() {
    s := trimRightSpace(`
    Ice Cream 

`)
    fmt.Printf(">>%s<<", s)
}

>>
    Ice Cream<<

As you can see we have now removed the new line and tab characters from the end of the string.

Trim Duplicate Whitespace in Go

If you want to remove duplicate whitespace in the middle of a string as well as all whitespace from the begining and end, that is also easy. Of course, we will use the strings package to help us with this.

To do this we will use two functions we have not talk about yet. We will use the strings.Fields() function. Which splits a string into a slice of strings arround consecutive whitespace characters. The whitespace characters used in strings.Fields() are from unicode.IsSpace() which is the same used in both the strings.TrimSpace() function as well as our own left and right trim functions.

Once we have a slice of strings with no whitespace characters we can simply join them all into a single string with spaces in between. The strings.Join() is perfect for this.

Let's see how this works...

package main

import (
    "fmt"
    "strings"
)

func trimAllSpace(s string) string {
    return strings.Join(strings.Fields(s), " ")
}

func main() {
    s := trimAllSpace(`
    Ice

     Cream 

`)
    fmt.Printf(">>%s<<", s)
}

>>Ice Cream<<

As you can see both the new line, tab and space characters were removed from the end, beginning, and all duplicate whitespace characters were replaced by a single space.

Go's Other Trim Functions

There are three other trim functions that come in the Go standard library that are very helpful but have not been talked about. These functions are for more than just removing whitespace from a string. They can be used to remove any set of characters from the left or right side of a string.

  1. strings.Trim()
  2. strings.TrimLeft()
  3. strings.TrimRight()

strings.Trim()

The strings.Trim() function takes a cutset as the second parameter. It will remove all characters at the beginning and end of the string that are in the cutset.

For example, could achive similar functionality to strings.TrimSpace() by calling strings.Trim(string, "\t\n\v\f\r "). However, you would be better to just use strings.TrimSpace() for this case.

Let's see strings.Trim() in action.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Trim("Peanut butter cup app", "Pp"))
}
eanut butter cup a

As you can see our cutset included both 'P' (uppercase) and 'p' (lowercase). Because of that, the leading P and ending pp were removed.

strings.TrimLeft()

The strings.TrimLeft() function works almost exactly like strings.Trim(). However, it only removes the characters in the cutset from the left side of the string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.TrimLeft("Oh Fudge!", "hO"))
}
 Fudge!

As you can see our leading characters in the cutset were removed. This can be helpful if you have a string that was left padded with whitespace for alignment reasons, but now you just want the value.

It is also worth noting that the order of characters in the cutset does not matter, as the previous example shows.

strings.TrimRight()

Yes, you guessed it. strings.TrimRight() works just like strings.TrimLeft(). It just removes characters from the right or trailing end of the string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.TrimRight("Caramel toppings", "s"))
}
Caramel topping

At this point, I am sure you know what is going on.

So, go trim some whitespace from that string in your Go code.

Daniel Morell

Daniel Morell

I am a fullstack web developer with a passion for clean code, efficient systems, tests, and most importantly making a difference for good. I am a perfectionist. That means I love all the nitty-gritty details.

I live in Wisconsin's Fox Valley with my beautiful wife Emily.

Daniel Morell

I am a fullstack web developer, SEO, and builder of things (mostly digital).

I started with just HTML and CSS, and now I mostly work with Python, PHP, JS, and Golang. The web has a lot of problems both technically and socially. I'm here fighting to make it a better place.

© 2018 Daniel Morell.
+ Daniel + = this website.