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
Syntax
func Contains(s, substr string) bool func HasPrefix(s, prefix string) bool func Index(s, substr string) int
Parameters
| Parameter | Description |
|---|---|
Contains / ContainsAny |
Substring / any of these characters. |
HasPrefix / HasSuffix |
Starts / ends with. |
Index / LastIndex |
Byte offset, or -1. |
EqualFold |
Case-insensitive equality. |
Examples
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.
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.
Related
strings.Split and strings.Join· Split a string into a slice around a separator, and join a slice of strings with a separator.- Go Strings · tutorial