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 check lowercase characters in a string in Golang?
How to check if a string contains a white space in Golang?
Strip all white spaces, tabs, newlines from a string
How to trim leading and trailing white spaces of a string in Golang?
How to check if a string contains a substring in Golang?
How to check string contains uppercase lowercase character in Golang?
Most Helpful This Week
Sierpinski triangle in Go Programming LanguageHow to wait for Goroutines to Finish Execution?Passing multiple string arguments to a variadic functionGolang HTTP GET request with parametersGolang import package inside packageHow do you write multi-line strings in Go?How to find length of Map in Go?Data encryption with AES-GCMConvert Float32 to Float64 and Float64 to Float32Different ways to validate JSON string