Welcome To Golang By Example

Replace some instances of a substring with another in Go (Golang)

Table of Contents

Overview

In GO string are UTF-8 encoded. strings package of GO provides a Replace method that can be used to replace some non-overlapping instances of a given substring with a new substring. It returns a copy of the string
Below is the signature of the function.

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

Let’s look at the working code

Code:

package main

import (
    "fmt"
    "strings"
)

func main() {
    res := strings.Replace("abcdabxyabr", "ab", "12", 1)
    fmt.Println(res)

    res = strings.Replace("abcdabxyabr", "ab", "12", -1)
    fmt.Println(res)
}

Output:

12cdabxyabr
12cd12xy12r