How to Trim Leading and Trailing White Spaces of a String in Go

Created
Modified

Using strings.TrimSpace Function

The easiest way to trim leading and trailing white spaces of a string in Golang. For example,

package main

import (
  "fmt"
  "strings"
)

func main() {
  s := "  \t \n Hello \r\n  "

  t := strings.TrimSpace(s)
  fmt.Printf("%q\n", t)
}
"Hello"

Using strings.Trim Function

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

See the following example:

package main

import (
  "fmt"
  "strings"
)

func main() {
  s := "  \t \n Hello \r\n  "

  fmt.Printf("%q\n", strings.Trim(s, " \n\t"))
  fmt.Printf("%q\n", strings.Trim(s, "\n "))
}
"Hello \r"
"\t \n Hello \r"

Using strings.TrimLeft or strings.TrimRight

To remove only the leading or the trailing characters, use strings.TrimLeft or strings.TrimRight. For example,

package main

import (
  "fmt"
  "strings"
)

func main() {
  s := "  \t \n Hello \r\n  "

  t := strings.TrimLeft(s, " \t\n")
  t = strings.TrimRight(t, "\n ")
  fmt.Printf("%q\n", t)
}
"Hello \r"

Related Tags