How to Replace String in Golang?

How to Replace String in Golang?

In this blog, we will learn How to Replace String in Golang, using Replace and ReplaceAll Function present in the strings package.

Learn about How to split String by delimiter? and also Split string using FieldsFunc

Golang String Replace

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

The strings.Replace() function takes a string to work on, a substring to find, a replacement string, and the number of replacements to make (-1 meaning as many as possible), and returns a string with all the (non-overlapping) replacements performed.

Example:

s := `Go is strongly statically typed language. Go is easy to learn. Go is called the future of the server-side language.`
fmt.Println(strings.Replace(s, "Go", "Golang", 2))

Output:

Golang is strongly statically typed language. Golang is easy to learn. Go is called the future of the server-side language.

To make all the replacements in the string, make n in the Replace function as -1.

Golang ReplaceAll

The Golang ReplaceAll Function as the name suggests replaces all the old string with the new string.

s := `Go is strongly statically typed language. Go is easy to learn. Go is called the future of the server-side language.`
fmt.Println(strings.ReplaceAll(s, "Go", "Golang"))

Output:

Golang is strongly statically typed language. Golang is easy to learn. Golang is called the future of the server-side language.

The ReplaceAll Function in Golang is basically the Replace function with -1 as the last parameter.

Learn more aboutĀ Golang Strings Package from theĀ official Documentation.

Tags:

Leave a Reply

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