Every developer needs to know how to work with strings in the language they are using. The Go libraries makes replacing parts of strings easy for a developer. I will show three solutions for replacing parts of a string in Go.
Solution 1
The simple way is to use the Replace function from the strings package. This function takes in four values:
<a href="https://medium.com/media/43d9351ad089b4470f014a0ae8bd5466/href">https://medium.com/media/43d9351ad089b4470f014a0ae8bd5466/href</a>
This is the output:
Mary had a little Gopher Gopher duck
If we change line 13 above to:
out := strings.Replace(refString, "duck", "dog", -1)
This is the output:
Mary had a little Gopher Gopher Gopher
Solution 2
When you have more than one string value to replace you should use the NewReplacer function from the strings packages. This function returns a new Replacer from a list of old, new string pairs. This method can be use to replace multiple string a once.
<a href="https://medium.com/media/d6abfd854b89c827ad40411162c62836/href">https://medium.com/media/d6abfd854b89c827ad40411162c62836/href</a>
This is the output:
John had a little Gopher Gopher
Solution 3
The more sophisticated way of replaces substring is to use regular expression or regex. For this solution, we will use the MustCompile and ReplaceAllString from the regexp package.
<a href="https://medium.com/media/e44a348cecd264aeebdd47a502bdb947/href">https://medium.com/media/e44a348cecd264aeebdd47a502bdb947/href</a>
This would output:
Mary had a little Gropher Gopher
Originally published at harrisonbrock.com.