Go – Trim Spaces around String

To trim spaces around string in Go language, call TrimSpace function of strings package, and pass the string as argument to it.

The syntax to trim/remove white spaces at the leading and trailing edges of a string str using TrimSpace function is


TrimSpace function returns a String.


In the following example, we take a string, str that has leading and trailing spaces. We trim these leading and trailing spaces using TrimSpace function.


package main

import (

func main() {
	var str = "   Hello World   "
	var result = strings.TrimSpace(str)
	fmt.Println("Original String : ", str)
	fmt.Println("Trimmed  String : ", result)


Original String :     Hello World   
Trimmed  String :  Hello World


In this Golang Tutorial, we learned how to trim spaces around a string in Go programming language, with the help of example programs.