Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท strings and strconv

Go strings.HasPrefix() and HasSuffix() functions

Reference for Go strings.HasPrefix, HasSuffix, CutPrefix and CutSuffix: test how a string starts or ends and remove the affix in one step, with edge cases.

strings.HasPrefix(s, prefix) reports whether s begins with prefix, and strings.HasSuffix(s, suffix) reports whether it ends with suffix. They are the simplest way to check file extensions, URL schemes, command names and protocol markers.

Go 1.20 added CutPrefix and CutSuffix, which do the test and the removal together and return a found flag.

Go
ok := strings.HasPrefix("golang", "go") // true

Try it

Go Testing prefixes and suffixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go CutPrefix and CutSuffix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func HasPrefix(s, prefix string) bool
func HasSuffix(s, suffix string) bool
func CutPrefix(s, prefix string) (after string, found bool)
func CutSuffix(s, suffix string) (before string, found bool)
Name Description
s The string to examine.
prefix, suffix The exact text expected at the start or end. Case-sensitive.

Returns: HasPrefix and HasSuffix return a bool. CutPrefix returns the rest of s after the prefix and true; if the prefix is absent it returns s unchanged and false. CutSuffix is the mirror image.

Edge cases: an empty prefix or suffix always matches. If the affix is longer than s the result is false. Nothing panics, and no allocation occurs (results are substrings).

Usage notes

  • Prefer CutPrefix over HasPrefix followed by TrimPrefix; it avoids repeating the literal and the len(prefix) arithmetic that used to cause off-by-one bugs.
  • Case-insensitive: compare a slice of the string with strings.EqualFold, for example len(s) >= 4 && strings.EqualFold(s[:4], "http") (watch for multi-byte characters), or lowercase first.
  • Many prefixes: loop over a slice of candidates, or use a switch with case strings.HasPrefix(...).
  • File extensions: strings.HasSuffix(name, ".go") works, but filepath.Ext is more robust for paths.
  • Not the same as Contains. HasPrefix only looks at the start; use strings.Contains() for anywhere.
  • Performance: both are constant time apart from the comparison itself (length check plus memequal).
  • Bytes: bytes.HasPrefix and bytes.HasSuffix are the []byte versions.