Trim leading and trailing whitespace

Use the strings.TrimSpace function to remove leading and trailing whitespace as defined by Unicode.

s := strings.TrimSpace("\t Goodbye hair!\n ")
fmt.Printf("%q", s) // "Goodbye hair!"

To remove other leading and trailing characters, use strings.Trim. To remove only the leading or the trailing characters, use strings.TrimLeft or strings.TrimRight.

Further reading

The String functions cheat sheet presents the top Go string functions.

Share this page: