Skip to content

How to Generate Slug in a GoLang?

ToSlug generates a slug from a given string. It removes special characters, converts spaces to dashes, trims leading and trailing spaces, and converts the entire string to lowercase.

Parameters:

  • input: The string to be converted to a slug.

Returns:

  • The generated slug.
func ToSlug(input string) string {
	// Remove special characters
	reg, _ := regexp.Compile("[^a-zA-Z0-9]+") 

	// Replace special characters with spaces
	processedString := reg.ReplaceAllString(input, " ")

	// Remove leading and trailing spaces
	processedString = strings.TrimSpace(processedString)

	// Replace spaces with dashes
	slug := strings.ReplaceAll(processedString, " ", "-")

	// Convert to lowercase
	slug = strings.ToLower(slug)

	return slug // Return the generated slug
}

Experience the magic of coding unfold as you execute this code!

package main

import (
	"fmt"

	"regexp"
	"strings"
)

func ToSlug(input string) string {
	reg, _ := regexp.Compile("[^a-zA-Z0-9]+")

	processedString := reg.ReplaceAllString(input, " ")

	processedString = strings.TrimSpace(processedString)
	slug := strings.ReplaceAll(processedString, " ", "-")
	slug = strings.ToLower(slug)
	return slug
}

func main() {
	fmt.Println(ToSlug("Hello World!")) // hello-world

	fmt.Println("Build with love by Adam Nasrudin")
}

enjoy your code!