OneBite.Dev - Coding blog in a bite size

replace multiple words in a string in Go

Code snippet on how to replace multiple words in a string in Go

  package main

import "strings"

func ReplaceWords(source, old, new string) string {
    return strings.Replace(source, old, new, -1)
}

func main() {
    message := "It was a beautiful day today."
    replacedMsg := ReplaceWords(message, "beautiful", "gorgeous")
    println(replacedMsg)
}

This code sample shows you how to replace words in a string in Go. The function takes in three parameters: the source string, the old word to be replaced, and the new word to replace it. It uses strings.Replace() to replace the old word (third parameter) with the new word (fourth parameter). In this case, it replaces “beautiful” with “gorgeous”. In the main, it sets the source message to “It was a beautiful day today.” and then calls the ReplaceWords() function. The output is the replaced message, which prints out “It was a gorgeous day today.”

go