Go – Replace Substring in a String

To replace a substring in string with a new value in Go programming, we can use either Replace function or ReplaceAll function of the strings package.

Replace function replaces only specified N occurrences of the substring, while ReplaceAll function replaces all the occurrences of given substring with the new value.

The syntax of Replace function is

strings.Replace(str, replace, newValue, n)

Replace function returns a new string with the first n occurrences of replace string replaced with newValue string in str string.

If n is -1, then there is no limit on the number of replacements.

The syntax of ReplaceAll function is

strings.ReplaceAll(str, replace, newValue)

ReplaceAll function returns a new string with all occurrences of replace string replaced with newValue string in str string.

Examples

Let us go through some of the examples using Replace and ReplaceAll functions.

Replace

In the following example, we take a string, str and replace first 2 occurrences of the substring replace with a new value newValue.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Abc Abc Abc Abc Abc"
	replace := "Abc"
	newValue := "Mnop"
	n := 2
	result := strings.Replace(str, replace, newValue, n)
	fmt.Println("Original String : ", str)
	fmt.Println("Result   String : ", result)
}

Output

Original String :  Abc Abc Abc Abc Abc
Result   String :  Mnop Mnop Abc Abc Abc

As specified via n, only the first two occurrences have been replaced.

Now, let us set n with -1. All the occurrences of the replace string must be replaced with the new value.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Abc Abc Abc Abc Abc"
	replace := "Abc"
	newValue := "Mnop"
	n := -1
	result := strings.Replace(str, replace, newValue, n)
	fmt.Println("Original String : ", str)
	fmt.Println("Result   String : ", result)
}

Output

Original String :  Abc Abc Abc Abc Abc
Result   String :  Mnop Mnop Mnop Mnop Mnop

ReplaceAll

In the following example, we take a string, str and replace all the occurrences of the substring replace with a new value newValue.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Abc Abc Abc Abc Abc"
	replace := "Abc"
	newValue := "Mnop"
	result := strings.ReplaceAll(str, replace, newValue)
	fmt.Println("Original String : ", str)
	fmt.Println("Result   String : ", result)
}

Output

Original String :  Abc Abc Abc Abc Abc
Result   String :  Mnop Mnop Mnop Mnop Mnop

All the occurrences of the given substring are replaced with new value.

Conclusion

In this Golang Tutorial, we learned how to replace a substring with new value in a string, in Go programming language, with the help of example programs.