In this blog post, I will show you how you can replace parts of a string with new content. To complete this task, we will use the strings package from the Go (GoLang) Standard Library.
The Replace function is used for when you need simple replace and the function takes in four parameters:
In the example below will replace the two first strings Duck with Gopher.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package main import ( "strings" "fmt" ) const refString = "Bill had a little Duck Duck Duck" func main() { // Use this for simple replacement // This will replace the first two "Duck" Strings with "Gopher" out := strings.Replace(refString, "Duck", "Gopher", 2) fmt.Println(out) } |
You can run this code in the Go Playground here.
If you want to replace all the strings that match the value Duck you can use a -1 for the n parameter. The example below shows this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package main import ( "strings" "fmt" ) const refString = "Bill had a little Duck Duck Duck" func main() { // Use this for simple replacement // This will replace all strings that match "Duck" with "Gopher" out := strings.Replace(refString, "Duck", "Gopher", -1) fmt.Println(out) } |
You can run this code in the Go Playground here.
In this blog post, you learned how to replace parts of strings using the Replace functions. In later blog posts, I will show you other methods of replacing parts of a string.
Harrison Brock is a software engineer that focuses on Full Stack web development