25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Replacing All Occurrences in a String in Go
Code Snippet

Replacing All Occurrences in a String in Go

go

The strings.ReplaceAll function replaces all occurrences of a substring with a replacement string, returning a new string without modifying the original. This is the most straightforward approach when you want to replace every instance of a particular substring. Go strings are immutable, so all replacement operations return new string values.

For more granular control, strings.Replace allows you to specify a maximum number of replacements to perform. By passing -1 as the count parameter, Replace behaves identically to ReplaceAll. This function is useful when you want to replace only the first few occurrences or when the count is dynamic.

Here’s a comprehensive example demonstrating both replacement functions:

package main

import (
  "fmt"
  "strings"
)

func main() {
  // Using ReplaceAll to replace all occurrences
  text := "apple apple apple banana apple"
  result1 := strings.ReplaceAll(text, "apple", "orange")
  fmt.Println(result1) // Output: orange orange orange banana orange

  // Using Replace to limit replacements
  result2 := strings.Replace(text, "apple", "orange", 2)
  fmt.Println(result2) // Output: orange orange apple banana apple

  // Replace with -1 is equivalent to ReplaceAll
  result3 := strings.Replace(text, "apple", "orange", -1)
  fmt.Println(result3) // Output: orange orange orange banana orange

  // Practical example: template variable substitution
  template := "Hello {{name}}, welcome to {{place}}!"
  final := strings.ReplaceAll(template, "{{name}}", "Alice")
  final = strings.ReplaceAll(final, "{{place}}", "Wonderland")
  fmt.Println(final) // Output: Hello Alice, welcome to Wonderland!
}

String replacement is a fundamental operation in text processing, configuration management, and templating tasks. Understanding the difference between ReplaceAll and Replace with limited counts allows you to handle both simple and complex string transformation scenarios effectively in your Go applications.

Further Reading:

If you found this snippet useful, you may also enjoy some of the other content on the site: