Replacing Parts of a String in Go Part One

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 Standard Library.

Replace Function

The Replace function is used for when you need simple replace and the function takes in four parameters:

  1. s: This is the reference string.
  2. old: This is the value in the string we want to change.
  3. new string: This is the new string value.
  4. n: This is the number of times to do the replacement.

In the example below will replace the two first strings Duck with  Gopher.

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 parameter. The example below shows this.

You can run this code in the Go Playground here.

Conclusion

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.

About the Author Harrison Brock

Harrison Brock is a software engineer that focuses on Full Stack web development

follow me on: