Slugify a String of Text in Golang
Published: 2024-05-17 | Updated: 2024-05-24Here is a function which takes an input string and converts it to a “slug”, a string of text suitable for use in an url address
func slugify(text string) string {
// Convert spaces to hyphens
text = strings.ReplaceAll(text, " ", "-")
// Remove non-alphanumeric characters and hyphens
// at the beginning and end
reg := regexp.MustCompile("[^a-zA-Z0-9-]+")
text = reg.ReplaceAllString(text, "")
// Convert to lowercase
text = strings.ToLower(text)
return text
}
Be aware, though. It’s only a simple thing. I made it as part of a site conversion I was working on. All I wanted out of it was to take a plain text string with no special characters, convert it to lowercase and replace spaces with hyphen.