Home »
Golang »
Golang Reference
Golang bytes.ReplaceAll() Function with Examples
Golang | bytes.ReplaceAll() Function: Here, we are going to learn about the ReplaceAll() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 25, 2021
bytes.ReplaceAll()
The ReplaceAll() function is an inbuilt function of the bytes package which is used to get a copy of the byte slice (s) with all non-overlapping instances of old replaced by new. Where old is the byte slice to be replaced and new is the byte slice to be replaced with.
It accepts three parameters (s, old, new []byte) and returns a copy of the slice s with all non-overlapping instances of old replaced by new.
Note:
- If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice.
Syntax
ReplaceAll(s, old, new []byte) []byte
Parameters
- s : The byte slice in which we have to make the replacement.
- old : The byte slice to be replaced.
- new : The byte slice to be replaced with.
Return Value
The return type of the bytes.ReplaceAll() function is a []byte, it returns a copy of the slice s with all non-overlapping instances of old replaced by new.
Example 1
// Golang program to demonstrate the
// example of bytes.ReplaceAll() function
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Printf("%s\n", bytes.ReplaceAll(
[]byte("Alone, alone, all all alone"),
[]byte("all"), []byte("none")))
fmt.Printf("%s\n", bytes.ReplaceAll(
[]byte("Alone, alone, all all alone"),
[]byte("all"), []byte("none")))
fmt.Printf("%s\n", bytes.ReplaceAll(
[]byte("Alone, alone, all all alone"),
[]byte("alone"), []byte("happy")))
}
Output:
Alone, alone, none none alone
Alone, alone, none none alone
Alone, happy, all all happy
Example 2
// Golang program to demonstrate the
// example of bytes.ReplaceAll() function
package main
import (
"bytes"
"fmt"
)
func main() {
var str string
var old string
var new string
var result []byte
str = "Alone, alone, all all alone"
old = "all"
new = "none"
result = bytes.ReplaceAll(
[]byte(str), []byte(old), []byte(new))
fmt.Printf("str: %s\n", str)
fmt.Printf("old: %s\n", old)
fmt.Printf("new: %s\n", new)
fmt.Printf("result: %s\n", result)
fmt.Println()
old = "alone"
new = "happy"
result = bytes.ReplaceAll(
[]byte(str), []byte(old), []byte(new))
fmt.Printf("str: %s\n", str)
fmt.Printf("old: %s\n", old)
fmt.Printf("new: %s\n", new)
fmt.Printf("result: %s\n", result)
}
Output:
str: Alone, alone, all all alone
old: all
new: none
result: Alone, alone, none none alone
str: Alone, alone, all all alone
old: alone
new: happy
result: Alone, happy, all all happy
Golang bytes Package »