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
Unveiling the Potential of Quantum Computing in AI: A Game Changer for Industries
Add Method to Struct Type
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
GO Program to Calculate Area of Rectangle and Square
Golang program for implementation of Tower of Hanoi Algorithm
Interface embedding another interface in Go Programming Language
Most Helpful This Week
How to convert Go struct to JSON?How to Unmarshal nested JSON structure?Dereferencing a pointer from another packageHow do you write multi-line strings in Go?How to read names of all files and folders in current directory?How can I convert a string variable into Boolean, Integer or Float type in Golang?Strip all white spaces, tabs, newlines from a stringHigher Order Functions in GolangHow to import structs from another package in Go?Example to compare Println vs Printf