What is strings.Replace() Function in Golang

Golang strings.Replace() function is “used to return a copy of the given string with the first n non-overlapping instances of old replaced by new one.”

Syntax

func Replace(s, old, new string, n int) string

Parameters

  1. s: This is the given string.
  2. old: This is the string to be replaced.
  3. new: This is the string that replaces the old one.
  4. n: This is the number of times the old string is replaced.

Note: If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

Return value

The Replace() function returns a new string with the specified replacements.

Example 1

package main

import (
  "fmt"
  "strings"
)

func main() {
  // Original string
  s := "I love Go! Go is great! Go Go Go!"

  // Replacing all occurrences of "Go" with "Golang"
  result1 := strings.Replace(s, "Go", "Golang", -1)
  fmt.Println("All replacements:", result1)

  // Replacing the first two occurrences of "Go" with "Golang"
  result2 := strings.Replace(s, "Go", "Golang", 2)
  fmt.Println("First two replacements:", result2)
}

Output

All replacements: I love Golang! Golang is great! Golang Golang Golang!
First two replacements: I love Golang! Golang is great! Go Go Go!

Example 2

package main

import (
  "fmt"
  "strings"
)

// Function to apply multiple replacements to a given string
func replaceMultiple(s string, replacements map[string]string) string {
  for old, new := range replacements {
    s = strings.Replace(s, old, new, -1)
  }
  return s
}

func main() {
  // Original text with placeholders
  text := `Dear {name},

  We are pleased to inform you that you have been accepted 
  for the {position} position at {company}.

  Start Date: {start_date}
  Location: {location}

  Best Regards,
  {company}
`
  // Mapping of placeholders to their replacements
  replacements := map[string]string{
    "{name}": "John Doe",
    "{position}": "Software Engineer",
    "{company}": "TechCorp",
    "{start_date}": "August 15, 2023",
    "{location}": "New York",
  }

  // Applying the replacements to the original text
  updatedText := replaceMultiple(text, replacements)

  // Printing the updated text
  fmt.Println(updatedText)
}

Output

strings.Replace() Function in Golang

That’s it!

Related posts

Check If String Contains Substring in Golang

Leave a Comment