Search and Replace Strings in Golang – Top 5 Examples
Tags: go
Published: 2021-04-21 13:20:55

---
title: Search and Replace Strings in Golang – Top 5 Examples
published: true
date: 2021-04-20 13:13:00 UTC
tags: Golang
canonical_url: https://qvault.io/golang/replace-strings-golang/
---

 ![replace lightbulb](https://qvault.io/wp-content/uploads/2021/04/replace-lightbulb.jpeg "replace lightbulb")

The post [Search and Replace Strings in Golang – Top 5 Examples](https://qvault.io/golang/replace-strings-golang/) first appeared on [Qvault](https://qvault.io).

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()](https://golang.org/pkg/strings/#Replace) function. `strings.Replace()` returns a _copy_ of its input string after searching and replacing all instances of the given substring with a new one.

## strings.Replace() signature

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

Notes

- `s` is the original string that contains parts that need to be changed.
- `old` is the substring you want to be replaced.
- `new` is the substring that will be swapped out for `old`.
- `n` limits the number of replacements. If you want to replace them all, just set `n` to `-1`, or use the more explicit [ReplaceAll](https://golang.org/pkg/strings/#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](https://qvault.io/golang/split-strings-golang/).

```go
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`.

```go
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 certain characters. For example, you may want to remove all periods. You can simply replace all periods with an empty string.

```go
package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Replace("123.456.789.0", ".", "", -1))
    // prints "1234567890"
}
```

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

If you have the same replacements and need to perform those operations on many different _documents_, it can make sense to initialize a [Replacer](https://golang.org/pkg/strings/#Replacer), which will be much faster when used repeatedly. The reason it’s faster is it builds a [trie structure](https://en.wikipedia.org/wiki/Trie) under the hood that it keeps in memory, and that structure can be used repeatedly.

```go
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()](https://golang.org/pkg/strings/#NewReplacer) takes a list of old-new string pairs, so you can use it to perform many different replacement operations.

```go
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](https://golang.org/pkg/regexp) package. This package exposes a [ReplaceAllString()](https://golang.org/pkg/regexp/#Regexp.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 really fluent in regular expressions.

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

Thanks for reading, now take a course!

Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.

[Start coding now](https://qvault.io)

### Questions?

Follow and hit me up on Twitter [@q\_vault](https://twitter.com/q_vault) if you have any questions or comments. If I’ve made a mistake in the article be sure to [let me know](https://qvault.io/contact/) so I can get it corrected!

[Subscribe](https://mailchi.mp/5c7f5c281bbe/qvault-newsletter-subscribe) to my newsletter for more coding articles delivered straight to your inbox.