Learn coding concepts by building real projects with modern technologies

Search and Replace Strings in Golang - Top 5 Examples

By Lane Wagner on Apr 20, 2021

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 the given substring with a new one.

strings.Replace() signature

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

Notes

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"
}

Learn Go by writing Go code

I'm a senior engineer learning Go, and the pace of Boot.dev's Go Mastery courses has been perfect for me. The diverse community in Discord makes the weekly workshops a blast, and other members are quick to help out with detailed answers and explanations.

- Daniel Gerep from Cassia, Brasil

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"
}

Learn JavaScript by building real projects

I was a field service engineer and I wanted to learn to code, but work and family limited my options. When I found Boot.dev, the "Intro to Coding in JavaScript" course got me up and running immediately, and I knew I made the right decision as soon as I joined the Discord community.

- Özgür Yildirim from Germany

Example #4 - Replacing in multiple strings (high performance)

If you need to perform the same replacements on many different documents, it can make sense to initialize a Replacer, which is much faster 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"
}

Learn to code by building real projects

Related Reading