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.
s := strings.ReplaceAll("oink oink", "k", "ky") // "oinky oinky"
Try it
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.
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
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
ReplaceAllwhen 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.Mapcan 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.Replaceis the[]bytetwin. - HTML and SQL: do not use
Replacefor escaping. Usehtml.EscapeStringand parameterized queries.