BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Replace Text

Go 1.23

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 n occurrences.
  • Efficiency: Both are optimized for speed.

Code Breakdown

13
Using 'strings.ReplaceAll'. This is the standard way to do a "find and replace" for everything in the string. It returns a new string.
18
Using 'strings.Replace' with a limit. Passing '1' tells Go to stop after the first replacement. This is useful for fixing prefixes or specific formatting.