Go 1.27 reference · Formatting, Strings and Text

Go strings.Contains, HasPrefix and Index Function

Check whether a string contains, starts or ends with a substring, and find its position.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func Contains(s, substr string) bool   func HasPrefix(s, prefix string) bool   func Index(s, substr string) int

Parameters

ParameterDescription
Contains / ContainsAny Substring / any of these characters.
HasPrefix / HasSuffix Starts / ends with.
Index / LastIndex Byte offset, or -1.
EqualFold Case-insensitive equality.

Examples

Example 1
package main

import (
	"fmt"
	"strings"
)

func main() {
	path := "/api/v2/orders"
	fmt.Println(strings.HasPrefix(path, "/api/"), strings.HasSuffix(path, "s"))
	fmt.Println(strings.Contains(path, "v2"), strings.Index(path, "orders"))
	fmt.Println(strings.EqualFold("Go", "GO"))
}

Output

true true
true 8
true

Run this on your computer — see “Get Started” for setup.

Trimming, replacing and case
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimPrefix("v1.27.3", "v"), strings.TrimSpace("  x  "))
	fmt.Println(strings.ReplaceAll("a-b-c", "-", "/"), strings.ToUpper("go"))
}

Output

1.27.3 x
a/b/c GO

Run this on your computer — see “Get Started” for setup.

Was this page helpful?