Go by Example: Replace Text
Replacing substrings is simple with `strings.Replace` and `strings.ReplaceAll`.
Code
package main
import (
"fmt"
"strings"
)
func main() {
s := "foo bar foo"
// 1. Replace All (Most Common)
// Replaces every instance of "foo" with "baz".
all := strings.ReplaceAll(s, "foo", "baz")
fmt.Println(all) // "baz bar baz"
// 2. Replace First N
// Replaces only the first 1 instance.
first := strings.Replace(s, "foo", "baz", 1)
fmt.Println(first) // "baz bar foo"
// 3. Replace with Limit
// -1 is equivalent to ReplaceAll.
unlimited := strings.Replace(s, "foo", "baz", -1)
fmt.Println(unlimited) // "baz bar baz"
}
Explanation
The strings package provides two primary functions for text substitution: strings.Replace and strings.ReplaceAll. For most use cases where you need to swap every occurrence of a substring, strings.ReplaceAll is the preferred choice due to its clarity and intent. It internally calls strings.Replace with a count of -1, ensuring all instances are updated.
When you need more granular control—such as replacing only the first occurrence of a typo or limiting changes to a specific number—strings.Replace allows you to specify exactly how many substitutions to perform. This is particularly useful for processing structured text where only the first match (like a header) should be modified while leaving subsequent matches untouched.
- strings.ReplaceAll: Replaces every occurrence.
- strings.Replace: Replaces first
noccurrences. - Efficiency: Both are optimized for speed.

