How to Trim a String in Golang

There are the following methods to trim a string in Golang.

  1. Method 1: Using the TrimSpace() Function
  2. Method 2: Using the Trim() Function
  3. Method 3: Using the TrimLeft() Function
  4. Method 4: Using the TrimRight() Function
  5. Method 5: Using the TrimSuffix() Function
  6. Method 6: Using the TrimPrefix() Function

Method 1: Using the strings.TrimSpace() Function

The easiest way to trim a string in Go is to use the strings.TrimSpace() function. The TrimSpace() function takes one argument, which is a string, and removes leading and trailing white spaces from it.

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := " Bella Ramsey is Ellie! "
  fmt.Println("Before:", str)
  fmt.Println("After:", strings.TrimSpace(str))
}

Output

Before:  Bella Ramsay is Ellie!
After: Bella Ramsay is Ellie!

You can see that the TrimSpace() function removes the whitespace from the beginning and end of the string.

Method 2: Using the strings.Trim() Function

The strings.Trim() function takes two arguments: a string and a set of characters to trim all the leading and trailing Unicode code points specified in the function.

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "***Bella Ramsey**"
  fmt.Println("Before:", str)
  fmt.Println("After:", strings.Trim(str, "*"))
}

Output

Before: ***Bella Ramsey**
After: Bella Ramsey

Method 3: Using the strings.TrimLeft() Function

The strings.TrimLeft() function takes two arguments: a string and a set of characters to trim from the left end of the string.

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "***Bella Ramsey**"
  fmt.Println("Before:", str)
  fmt.Println("After:", strings.TrimLeft(str, "*"))
}

Output

Before: ***Bella Ramsey**
After: Bella Ramsey**

Method 4: Using the strings.TrimRight() Function

The strings.TrimRight() function takes two arguments: a string and a set of characters to trim from the right end of the string.

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "***Bella Ramsey**"
  fmt.Println("Before:", str)
  fmt.Println("After:", strings.TrimRight(str, "*"))
}

Output

Before: ***Bella Ramsey**
After: ***Bella Ramsey

Method 5: Using the TrimSuffix() Function

The strings.TrimSuffix() function takes two arguments: a string and a suffix string to trim from the end of the string. 

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "app.go"
  fmt.Println("Before:", str)
  fmt.Println("After:", strings.TrimSuffix(str, ".go"))
}

Output

Before: app.go
After: app

Method 6: Using the TrimPrefix() Function

The strings.TrimPrefix() function takes two arguments: a string and a prefix string to trim from the start of the string.

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "app.go"
  fmt.Println("Before:", str)
  fmt.Println("After:", strings.TrimPrefix(str, "app"))
}

Output

Before: app.go
After: .go

That’s it.

Leave a Comment