How to remove leading and trailing whitespace from strings in Go

Trimming whitespace from strings is a common operation in programming especially when dealing with user input. This article will show you how to complete such tasks using built-in functions provided by the Go standard library.

It’s quite easy to trim whitespace from both ends of a string in Go due to the presence of the strings.TrimSpace() method in the standard library. All you need to do is pass the original string to this method, and you’ll get a modified string back without any leading or trailing whitespace characters (as defined by Unicode).

str := "       So much space     "
fmt.Println(strings.TrimSpace(str)) // So much space

If you want to remove other leading or trailing characters other than whitespace characters, use the strings.Trim() method. It accepts the original string and the characters to be removed as its arguments.

fmt.Println(strings.Trim("(((Hello, World!)))", "()")) // Hello, World!

You can also take advantage of the strings.TrimLeft method and the strings.TrimRight() method to remove leading or trailing characters respectively.

fmt.Println(strings.TrimLeft("(((Hello, World!)))", "()")) // Hello, World!)))
fmt.Println(strings.TrimRight("(((Hello, World!)))", "()")) // (((Hello, World!

Thanks for reading, and happy coding!