180 words, 1 min read

Today, I'll show you how to do a case-insensitive string replace in Go.

By default, string replacement in Go is case-sensitive, but sometimes, that's not the desired behaviour.

The best way to tackle this problem is to use the regexp (regular expressions) package to do this.

You can do it with a simple function like this:

import (
"regexp"
)
func CaseInsensitiveReplace(subject string, search string, replace string) string {
searchRegex := regexp.MustCompile("(?i)" + search)
return searchRegex.ReplaceAllString(subject, replace)
}

The trick is in the regular expression pattern. The modifier i tells it to be case-insensitive.

This works flawlessly, however, there is one caveat: performance.

To give you an idea about the performance penalty, I wrote a simple benchmark:

import (
"testing"
)
func Benchmark_CaseInsensitiveReplace(b *testing.B) {
for n := 0; n < b.N; n++ {
twxstring.CaseInsensitiveReplace("{Title}|{Title}", "{title}", "My Title")
}
}
func Benchmark_CaseSensitiveReplace(b *testing.B) {
for n := 0; n < b.N; n++ {
strings.ReplaceAll("{Title}|{Title}", "{Title}", "My Title")
}
}

The results are pretty self-explanatory:

Benchmark_CaseInsensitiveReplace-4 420237 3384 ns/op 2119 B/op 24 allocs/op
Benchmark_CaseSensitiveReplace-4 8224800 190 ns/op 64 B/op 2 allocs/op