MacKenzie Software

String replace in Go

Posted by MacKenzie Software on June 12, 2020

When you are new to a language it's sometimes the simple things you spend time googling, and this was one of them I struggled to get a clear answer for - how do you do a string replacement in Golang?

In my example, I wanted to strip out quotations from a string in Go. The solution is

    myString = strings.Replace(myString, "\"", "", -1)

In your import statement, you need to include strings:

    import (

The format of the Replace function is:

    strings.Replace(string_to_replace, old_string, new_string, number_of_replacements)

The number_of_replacements parameter is an interesting one, I always find I want to replace all. If you set a value <0 (in my case -1) then it will replace all instances of that string.