A "slug" is a clean, human-readable version of a text string, commonly used in URLs to represent titles or names. For example, a title like "How to Create a Slug in Go" could become "how-to-create-a-slug-in-go" as the slug. In this article, we'll learn how to create a function in Go to generate a slug from a string.
What is a Slug?
A slug is a transformed version of a text string, often used in URLs to make the URL more readable for users and friendly to search engines. Slugs are formed by removing special characters, spaces and punctuation from the source string and replacing the spaces with dashes or underscores.
Creating a Go function to generate a slug
Here is a Go function that generates a slug from a text string:
package main
import (
"fmt"
"regexp"
"strings"
)
// Function to generate a slug from a string
func CreateSlug(input string) string {
// Remove special characters
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
panic(err)
}
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
}
func main() {
input := "How to Create a Slug in Go!"
slug := CreateSlug(input)
fmt.Println(slug) // Print: "how-to-create-a-slug-in-go"
}
In the CreateSlug
function, we follow these steps:
- We use the regular expression
[^a-zA-Z0-9]+
to remove all special characters from the input string. - Remove leading and trailing spaces from the processed string.
- Replace the remaining spaces with dashes.
- We convert the result to lowercase.
Using the function
In the example above, we used the CreateSlug
function to generate a slug from the string "How to Create a Slug in Go!". The result was "how-to-make-a-slug-in-go", which is a commonly used slug format in URLs.
You can use this function in any Go project where you need to generate slugs from text strings, for example to create user friendly URLs. Make sure you import the regexp
and strings
packages to successfully use this feature.
You now have a solid foundation for creating slugs from strings in Go. You can tailor this feature to your specific needs or integrate it into larger projects.