Replace() vs ReplaceAll() in Golang


ReplaceAll() function in Golang replaces all the occurrences of a given substring with a new value. In contrast, Replace() function is used to replace only some characters in a string with a new value. It replaces only a specified "n" occurrences of the substring.

Syntax

The syntax of ReplaceAll() is as follows −

func ReplaceAll(s, old, new string) string

Where,

  • s is the given string
  • old is the string which we want to replace, and
  • new is string which will replace the old string.

Example 1

Let us consider the following example −

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   r := "You've Got to Learn Golang String Functions."

   // Display the Strings
   fmt.Println("Given String: \n", r)

   // Using the ReplaceAll Function
   testresults := strings.Replace(r, "Go", "ReplaceAll" ,2)

   // Display the ReplaceAll Output
   fmt.Println("\n After Replacing: \n", testresults)
}

Output

It will generate the following output −

Given String:
You've Got to Learn Golang String Functions.
After Replacing:
You've ReplaceAllt to Learn ReplaceAlllang String Functions.

Observe that all occurrences of "Go" have been replaced with "ReplaceAll".

Example 2

Now, let's take an example to show the use of Replace() function, which will also highlight the difference between Replace() and ReplaceAll().

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   r := "You've Got to Learn Golang String Functions."

   // Display the Strings
   fmt.Println("Given String: \n", r)

   // Using the Replace Function
   testresults := strings.Replace(r, "Go", "ReplaceAll", 1)
   
   // Display the ReplaceAll Output
   fmt.Println("\n After Replacing: \n", testresults)
}

Output

On execution, it will produce the following output −

Given String:
You've Got to Learn Golang String Functions.

After Replacing:
You've ReplaceAllt to Learn Golang String Functions.

Here, you can notice that only one instance of "Go" has been replaced by the new value "ReplaceAll".

Updated on: 10-Mar-2022

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements