How to remove special characters from a string in GoLang?
Special characters typically include any character that is not a letter or number, such as punctuation and whitespace. Removing special characters from a string results in a string containing only letters and numbers.
Remove Special Characters
We use the ReplaceAllString() method from regex package to replace the matched non-alphanumeric characters with the empty string "".
Example
// Golang program to remove
// special characters from string
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang@%Programs#"
str = regexp.MustCompile(`[^a-zA-Z0-9 ]+`).ReplaceAllString(str, "")
fmt.Println(str)
}
Output
GolangPrograms
Most Helpful This Week
How to replace emoji characters in string using regex in Golang?Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]Different ways to convert Byte Array into StringHow to iterate over an Array using for loop?Find capacity of Channel, Pointer and SliceVarious examples of Carbon date-time package in GolangHow to read/write from/to file in Golang?How to Unmarshal nested JSON structure?Regular expression to extract all Non-Alphanumeric Characters from a StringHow can we reverse a simple string in Go?