How Replace a String in Go - Top 5 Examples
Go has a powerful standard library that makes string manipulation easy right out of the box. One of the functions I use most often is the strings package’s Replace() function. strings.Replace() returns a copy of its input string after replacing all instances of a given substring with a new one.
How to use strings.Replace in Go
Function signature:
func Replace(s, old, new string, n int) string
Example usage:
strings.Replace("one one two two three", "one", "1", -1)
// 1 1 two two three
Notes about the function:
sis the original string that contains the substrings to be replaced.oldis the substring you want to be replaced.newis the substring that will be swapped out forold.nlimits the number of replacements. If you want to replace them all, just setnto-1, or use the more explicit ReplaceAll function.
Example #1 - Replacing delimiters
Let’s say you have some comma-separated values, CSVs. Perhaps you want to separate each word with a space instead of a comma. This can be useful if you need to make your delimiters consistent so you can later split the string into a slice.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("apple,banana,orange,pear", ",", " ", -1))
// prints "apple banana orange pear"
}
Example #2 - Only replace some strings
It can be useful to only print the replace the first n instances of a word. For example, let’s say we had some text containing dialogue, like in a movie script. If you want to change the delimiter between the speaker and there lines to be a dash instead of a colon, but don’t want to replace any colons in the dialogue, you can set n=1.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("Lane: 'The box said price:1'", ":", " -", 1))
// prints "Lane - 'The box said price:1'"
}
Example #3 - Remove all instances of a string
Sometimes you just want to strip out specific characters. For example, you may want to remove all periods. To do so, you can simply replace all periods with an empty string.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("123.456.789.0", ".", "", -1))
// prints "1234567890"
}
Example #4 - High-performance string replacement
If you need to perform the same replacements on many different documents, it can make sense to initialize a Replacer, which is much faster that the strings.Replace function when used repeatedly. It’s faster is because it builds a trie structure under the hood that it keeps in memory, and that structure can be used repeatedly.
package main
import (
"fmt"
"strings"
)
func main() {
replacer := strings.NewReplacer(",", ":", "!", "?")
fmt.Println(replacer.Replace("hello,there!good,reader!"))
fmt.Println(replacer.Replace("glad,to!have,you!"))
fmt.Println(replacer.Replace("bye,now!thank,you!"))
// prints:
// hello:there?good:reader?
// glad:to?have:you?
// bye:now?thank:you?
}
NewReplacer() takes a list of old-new string pairs, so you can use it to perform many different replacement operations.
func NewReplacer(oldnew ...string) *Replacer
Example #5 - Complicated Replacements with Regex
We’re shifting packages entirely now, and will be using the standard library’s regexp package. This package exposes a ReplaceAllString() function that lets us do more complicated replacements using a standard regex. This may be useful if you need to do some dynamic replacements, or are fluent in regular expressions.
func (re *Regexp) ReplaceAllString(src, repl string) string
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`r.t`)
fmt.Println(re.ReplaceAllString("rat cat rot dog", "ram"))
// prints "ram cat ram dog"
re = regexp.MustCompile(`-.*-`)
fmt.Println(re.ReplaceAllString("-rasjdkajnsdt-hello world", ""))
// prints "hello world"
}
Related Articles
How and Why to Write Enums in Go
Apr 19, 2021 by Lane Wagner - Boot.dev co-founder and backend engineer
An enum (short for enumerator), is a set of named constant values. An enum is a powerful tool that allows developers to create complex sets of constants that have useful names and yet simple and unique values.
Splitting a String into a Slice in Golang
Apr 15, 2021 by Lane Wagner - Boot.dev co-founder and backend engineer
I can’t begin to tell you how often I split strings in Go. More often than not I’m just parsing a comma-separated list from an environment variable, and Go’s standard library gives us some great tools for that kind of manipulation.
For Loops in Go
Apr 10, 2021 by Lane Wagner - Boot.dev co-founder and backend engineer
For loops are a programmer’s best friend! They allow us execute blocks of code repeatedly and iterate over collections of items. In Go, there are several different ways to write one.
Using a High-Level RabbitMQ Client in Golang
Mar 10, 2021 by Lane Wagner - Boot.dev co-founder and backend engineer
So you might already know that the amqp package is awesome and you can get up and running with just 40-50 lines of simple code. Unfortunately, the bare-bones amqp library doesn’t handle a lot of the stuff you probably wish it did, things like reconnecting logic, the spawning of threads, queue and binding boilerplate, and flow control.