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
Naming Conventions for Golang Functions
How do you handle HTTP redirects in Go?
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)
How do you handle HTTP requests in Go?
GO Program to Check Armstrong Number
Example: How to use ReadAtLeast from IO Package in Golang?
Most Helpful This Week
Regular expression to extract DNS host-name or IP Address from stringHow can I convert a string variable into Boolean, Integer or Float type in Golang?User Defined Function Types in GolangHow to include and execute HTML template?Example of Switch Case with Break in For LoopRegular expression to validate phone numberHow to create a photo gallery in Go?How to check pointer or interface is nil?Regular expression to extract date(YYYY-MM-DD) from stringDifferent ways for Integer to String Conversions