Skip to content

How to Replace a Substring in a String in Golang?

If you want to simply replace a string then golang has a fantastic function Replace from strings package for you:

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

If n < 0, there is no limit on the number of replacements.

Simple code example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	myStr := "My name is Tom! Tom is my name! Do you like Tom?"

	fmt.Println(
		strings.Replace(myStr, "Tom", "Morteza", 1),
	)

	fmt.Println(
		strings.Replace(myStr, "Tom", "Morteza", 2),
	)

	fmt.Println(
		strings.Replace(myStr, "Tom", "Morteza", -1),
	)
}

Leave a Reply

Your email address will not be published. Required fields are marked *