Golang Trim String: Remove Whitespace, Prefix, and Suffix

Tech reviewed: Deepak Prasad
Golang Trim String: Remove Whitespace, Prefix, and Suffix

Use the strings package to clean the ends of a string: spaces for user input, punctuation for tokens, or a fixed https:// prefix for URLs. The APIs look similar, but cutset trimming (Trim, TrimLeft, TrimRight) behaves differently from literal trimming (TrimPrefix, TrimSuffix). The sections below follow that split and end with a cheat sheet and common mistakes.

Tested on: Go 1.22, 64-bit Linux; examples are standard library only.


Quick answer: TrimSpace, cutset Trim, literal prefix and suffix

Use strings.TrimSpace(s) to remove leading and trailing whitespace. Use strings.Trim(s, cutset) (or TrimLeft / TrimRight) when the second argument is a set of characters to strip from the ends. Use strings.TrimPrefix(s, prefix) and strings.TrimSuffix(s, suffix) when you need to remove one exact leading or trailing substring.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "  hello  \n"
	fmt.Printf("TrimSpace: %q\n", strings.TrimSpace(s))

	fmt.Printf("Trim cutset: %q\n", strings.Trim("\"value\"", "\"'"))

	fmt.Println(strings.TrimPrefix("https://example.com", "https://"))
	fmt.Println(strings.TrimSuffix("main.go", ".go"))
}
Output

You should see quoted hello without outer whitespace, value without the surrounding quotes, then example.com and main from the prefix and suffix calls.


Trim a String in Go

In Go, the strings package provides different functions to remove unwanted characters from the beginning and end of a string. Each call returns a new string; the original is unchanged.

Use strings.TrimSpace to remove whitespace

Use strings.TrimSpace() when you want to remove whitespace from the beginning and end of a string.

Whitespace can include spaces, tabs, newlines, carriage returns, and other Unicode space characters. TrimSpace does not remove spaces inside the string, so after trimming " Go Linux Cloud Tutorial " you still get internal gaps between words.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	outer := "   Golang Tutorial   "
	fmt.Printf("outer spaces: %q -> %q\n", outer, strings.TrimSpace(outer))

	mixed := "   Go Linux Cloud   Tutorial   "
	fmt.Printf("internal spaces kept: %q\n", strings.TrimSpace(mixed))
}
Output

The first line drops only leading and trailing space; the second line still contains the spaces between Go, Linux, Cloud, and Tutorial.

Use strings.Trim to remove specific characters

Use strings.Trim(s, cutset) when the second argument is a cutset: every rune in that string defines characters to strip from both ends until a rune outside the set appears. The order of characters inside cutset does not matter.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Trim("---Golang---", "-"))
	fmt.Println(strings.Trim("...///Golang///...", "./"))
	fmt.Println(strings.Trim("[[Golang]]", "[]"))
}
Output

You should see Golang printed three times: hyphens only, .// mix, and square brackets stripped from both ends.

Trim does not remove an exact substring. For example, strings.Trim(url, "https://") treats h, t, p, s, :, and / as a set of runes to peel from the ends—not the literal prefix https://. For schemes and paths, use TrimPrefix (covered below).


Remove Leading or Trailing Characters

TrimLeft and TrimRight use the same cutset rules as Trim, but only peel from one end. Use them when the other side must stay untouched (padding, path roots, trailing noise).

Remove characters from the left using strings.TrimLeft

TrimLeft only strips from the start. Leading zeros and leading slashes are typical uses.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimLeft("00012345", "0"))
	fmt.Println(strings.TrimLeft("///api/v1/users", "/"))
	fmt.Println(strings.TrimLeft("000123000", "0"))
}
Output

The first line is 12345; the second is api/v1/users with only the opening slashes removed. The third shows why TrimLeft is not “trim all zeros”: trailing 000 stay because the function does not look at the right side.

Remove characters from the right using strings.TrimRight

TrimRight only strips from the end.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimRight("filename.txt...", "."))
	fmt.Println(strings.TrimRight("/api/v1/users///", "/"))
	fmt.Println(strings.TrimRight("123000", "0"))
}
Output

You should get filename.txt, /api/v1/users, and 123, with internal slashes or dots unchanged.


Remove prefix or suffix from a string

Remove exact prefix using strings.TrimPrefix

strings.TrimPrefix(s, prefix) returns s with a single leading prefix removed if s starts with it; otherwise it returns s unchanged. It does not loop or interpret prefix as a set of runes.

Remove exact suffix using strings.TrimSuffix

strings.TrimSuffix(s, suffix) does the same at the end of the string.

Goal Prefer
Strip https:// once strings.TrimPrefix(s, "https://")
Strip trailing / strings.TrimSuffix(s, "/")
Strip .go extension strings.TrimSuffix(s, ".go")
go
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Only the first literal "pre:" is removed.
	fmt.Println(strings.TrimPrefix("pre:pre:value", "pre:"))
	fmt.Println(strings.TrimSuffix("archive.tar.gz", ".gz"))
	fmt.Println(strings.TrimSuffix("notes.txt.backup", ".backup"))
}
Output

The first line is pre:value (not value), which shows TrimPrefix does not loop. The next lines strip one exact suffix from the end.


TrimSpace vs Trim vs TrimPrefix

When to use each trim function

Function Removes Best for
strings.TrimSpace(s) Leading and trailing Unicode spaces Input lines, flags, config values
strings.Trim(s, cutset) Leading and trailing runes in cutset Quotes, markers, digit padding
strings.TrimLeft / TrimRight One side only Asymmetric cleanup
strings.TrimPrefix(s, prefix) One exact leading substring URL scheme, command prefix
strings.TrimSuffix(s, suffix) One exact trailing substring Extensions, trailing slash

Why Trim is not the same as TrimPrefix

Trim treats the second argument as a cutset of runes to peel from both ends, not a single substring. TrimPrefix removes one exact leading string (once). On "abba", Trim("abba", "a") strips every leading and trailing a, giving "bb", while TrimPrefix("abba", "a") removes only one leading a, giving "bba". For URL schemes or paths, prefer TrimPrefix so you never rely on cutset behavior by accident.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("Trim cutset a: %q\n", strings.Trim("abba", "a"))
	fmt.Printf("TrimPrefix a:  %q\n", strings.TrimPrefix("abba", "a"))

	s := "//onlyslashes//"
	fmt.Printf("Trim /:        %q\n", strings.Trim(s, "/"))
	fmt.Printf("TrimPrefix //: %q\n", strings.TrimPrefix(s, "//"))
}
Output

You should see "bb" versus "bba", then "onlyslashes" versus "onlyslashes//"—the slash example shows one-sided literal removal versus trimming every matching rune from both ends.


Common mistakes with Go string trim

Using Trim to remove an exact prefix

Prefer TrimPrefix / TrimSuffix for literal affixes; reserve Trim for character classes at the ends.

Expecting TrimSpace to remove spaces inside the string

Internal spaces need strings.Fields, ReplaceAll, or another approach depending on the requirement.

Forgetting strings are immutable

Trim functions return a new string. Write s = strings.TrimSpace(s) (or use the return value) or the original binding never changes.

Confusing cutset characters with substring removal

If the goal is “remove this whole substring once,” use TrimPrefix, TrimSuffix, or other strings helpers—not Trim with the substring as the cutset.


Go string trim cheat sheet

Goal Use
Remove leading and trailing whitespace strings.TrimSpace(s)
Remove custom characters from both ends strings.Trim(s, cutset)
Remove only from the start strings.TrimLeft(s, cutset) or TrimPrefix for a literal
Remove only from the end strings.TrimRight(s, cutset) or TrimSuffix for a literal
Remove exact prefix strings.TrimPrefix(s, prefix)
Remove exact suffix strings.TrimSuffix(s, suffix)

Which trim function should you use?

  • User input or file lines with stray spaces or newlines: TrimSpace.
  • Strip decorative characters from both ends: Trim (cutset).
  • Known scheme or extension: TrimPrefix / TrimSuffix.

For predicates that are not a fixed cutset, see strings.TrimFunc in the official docs; this article stays with the common four plus left/right Trim.


Summary

Golang trim string tasks boil down to three ideas: TrimSpace for whitespace at the ends, Trim and TrimLeft / TrimRight for runes taken from a cutset, and TrimPrefix / TrimSuffix for one exact leading or trailing substring. Mixing up cutset and substring is the usual bug—Trim("abba", "a") is not TrimPrefix("abba", "a"), and Trim(s, "/") is not the same intent as TrimPrefix(s, "//"). Always assign the return value because strings are immutable.


References


Frequently Asked Questions

1. How do I remove leading and trailing spaces in Go?

Use strings.TrimSpace(s). It handles tabs, newlines, and other Unicode whitespace at the ends of the string.

2. What is the difference between strings.Trim and strings.TrimPrefix?

Trim removes any runes from a cutset at both ends until a rune outside the set appears. TrimPrefix removes a single exact leading substring if present.

3. Does Trim remove a substring from the middle of a string?

No. Trim only affects the beginning and end, and only for runes in the cutset; use ReplaceAll or other helpers for internal edits.
Antony Shikubu

Systems Integration Engineer

Highly skilled software developer with expertise in Python, Golang, and AWS cloud services.

  • Mastering Ansible Automation
  • Docker and Kubernetes: The Complete Guide
  • Go: Data Structures, Algorithms and Design Patterns With Go
  • Go (programming language)
  • Python (programming language)
  • Amazon Web Services