Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท strings and strconv

Go strings.Replace() function

Reference for Go strings.Replace and ReplaceAll: substitute one substring for another, limit the number of replacements, and handle the empty-pattern edge case.

strings.Replace(s, old, new, n) returns a copy of s with the first n non-overlapping occurrences of old replaced by new. If n is negative, every occurrence is replaced. strings.ReplaceAll(s, old, new) is shorthand for the "all" case and reads better.

Both return a new string. The original is never modified because Go strings are immutable.

Go
s := strings.ReplaceAll("oink oink", "k", "ky") // "oinky oinky"

Try it

Go Replace and ReplaceAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Empty patterns and overlaps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Replace(s, old, new string, n int) string
func ReplaceAll(s, old, new string) string
Name Description
s The input string.
old The text to look for.
new The replacement. May be empty to delete matches.
n Maximum number of replacements. Negative means no limit; 0 means none.

Returns: the new string. If nothing is replaced (no match, n == 0 or old == new), the original string is returned without copying.

Edge cases: if old is empty, it matches at the start of the string and after each UTF-8 sequence, so ReplaceAll("abc", "", "-") gives -a-b-c-. Matching is case-sensitive.

Usage notes

  • Prefer ReplaceAll when you want all matches; Replace(s, a, b, -1) is easy to misread.
  • Case-insensitive replacement is not built in. Use regexp.MustCompile("(?i)fish").ReplaceAllString(s, "cat").
  • Several replacements at once are better handled by strings.NewReplacer, which makes a single pass and avoids the replaced text being altered by a later rule.
  • Replacement happens left to right and never re-examines inserted text, so ReplaceAll("ab", "a", "aa") does not loop forever.
  • Replacing one rune: strings.Map can replace or drop individual runes by a function.
  • Not for patterns. For wildcards or captures use regexp.
  • Complexity: a counting pass plus a build pass, with a single allocation for the result. bytes.Replace is the []byte twin.
  • HTML and SQL: do not use Replace for escaping. Use html.EscapeString and parameterized queries.