Skip to content

Replace all occurrences of a string in Go

To replace all occurrences of a string in a string, we can use strings.ReplaceAll function. It returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.


func ReplaceAll(s, old, new string) string


strings.ReplaceAll("Poop Poop Poop", "Poop", "Code")

An example from the Golang documentation.

package main

import (

func main() {
	fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo"))
See also  Append text to file in Go

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.