# How to search and replace texts in a string in Golang?

Go ProgrammingServer Side ProgrammingProgramming

We often want to replace certain strings or all the strings that match a pattern with some other string. In order to do that in Golang, we can either use the native functions that the strings package of Go's standard library provides us with or we can write the logic for the same on our own.

In this article, we will see different examples, where we will use the two most used functions of the strings package. These functions are −

• strings.Replace()

• strings.ReplaceAll()

Let's first consider the signature of these functions to know a little more about them.

## Syntax of strings.Replace()

func Replace(s, old, new string, n int) string
• The first parameter in the above function is the string that contains a substring that we want to match with another string for replacement.

• The second parameter is the substring that we want to replace with the new string.

• The third parameter is the string with which we want to replace the pattern that got matched in the string.

• The last parameter is the number of occurrences we want to replace.

It should be noted that if we want to replace all the occurrences that got matched with the pattern, then we should pass -1 as the last argument when we call the Replace function.

Let's explore an example of the Replace function to understand how it works.

## Example 1

Consider the code shown below.

package main
import (
"fmt"
"strings"
)
func main() {
var str string = "It is not is a string is"
res := strings.Replace(str, "is", "isn't", 2)
fmt.Println(res)
}

## Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

It isn't not isn't a string is

Notice how we are just replacing the first two occurrences of that matched string. In case we want to replace all the occurrences, we can use the code shown below.

## Example 2

Consider the code shown below.

package main
import (
"fmt"
"strings"
)
func main() {
var str string = "It is not is a string is"
res := strings.Replace(str, "is", "isn't", -1)
fmt.Println(res)
}

## Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

It isn't not isn't a string isn't

The strings.ReplaceAll() function behaves similar to Replace() with -1 as the last argument.

## Example 3

Consider the code shown below.

package main
import (
"fmt"
"strings"
)
func main() {
var str string = "It is not is a string is"
res := strings.ReplaceAll(str, "is", "isn't")
fmt.Println(res)
}

## Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

It isn't not isn't a string isn't
Updated on 21-Feb-2022 07:28:20