Slugify a String in Elixir
A slug, in the context of web development and content management systems, is a URL-friendly version of a string that typically
represents the title or name of a resource, such as a webpage, article, or blog post. Slugs are used to create clean and readable
URLs by removing special characters, spaces, and other non-alphanumeric characters from the original string. This makes the URL
more search engine-friendly and easier for users to understand. For example, the original string "Engineering at Labs: Part 1"
might have a slug version of engineering-at-labs-part-1
in the URL.
Elixir Slugify Function
This a small utility function that I wrote recently to auto generate slugs for dynamically generated URLs to access files stored on cloud storage.
Slugify function performs following steps:
- Converts a string to downcase and remove any leading or trailing spaces
- Converts graphemes into normal characters (e.g.
á
,é
) - Replaces non-alphanumeric characters with empty string
- Replaces multiple spaces or hyphens with a single hyphen
defmodule String do
def slugify(text) when is_binary(text) do
text
|> String.downcase()
|> String.trim()
|> String.normalize(:nfd)
|> String.replace(~r/[^a-z0-9\s-]/u, " ")
|> String.replace(~r/[\s-]+/, "-", global: true)
end
def slugify(_), do: ""
end
Playground
See the above Elixir's implementation in action in JavaScript