What is the NewReplacer function in Go?

The strings.NewReplacer() method is part of the strings package of Go. Through it, we create the Replacer object, which gives us an efficient way to perform multiple string replacements in one string. This helps to avoid the overhead of multiple sequential replacements by batching them in a single request.

Syntax

Let’s go over the syntax of the function:

func NewReplacer(oldnew ...string) *Replacer
The syntax of the NewReplacer method

The function takes varying number of string arguments as pairs. Each pair contains the string that needs to be replaced with the string that we want to replace. If the function gets an odd number of strings, then the function will return an error.

Code example

Let’s look at a code example to better understand this function:

package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// defining the original string
ogString:= "I have an apple and a banana"
// using the function
temp := strings.NewReplacer("apple", "orange", "banana", "grape")
replacedString := temp.Replace(ogString)
fmt.Println("Original:", ogString)
fmt.Println("Replaced:", replacedString)
}

Code explanation

Let’s explain the code above:

  • Lines 3–6: We import the required packages.

  • Line 11: We define the ogString variable to hold the string that we will be using the function on. This is the original string that you want to modify. It’s initialized with the value "I have an apple and a banana".

  • Line 13: We define the temp variable to create a Replacer object. It specifies that the occurrences of "apple" should be replaced with "orange" and that "banana" should be replaced with "grape".

  • Line 14: We call the Replacer() method of the temp object with the original string and store the result in a variable called replacedString. This variable holds the modified string after replacements have been made.

  • Lines 15–16: We print the original string and the replaced string.

Knowledge test

After understanding the implementation, let’s test your knowledge on different aspects of the NewReplacer() method.

1

What package in Go provides the NewReplacer function?

A)

fmt

B)

strings

C)

strconv

D)

reflect

Question 1 of 40 attempted

Unlock your potential: Golang series, all in one place!

To continue your exploration of Golang, check out our series of Answers below:

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved