Created
March 11, 2024 08:22
-
-
Save crbelaus/a76d75941330b72523eddb2acd99cc71 to your computer and use it in GitHub Desktop.
Slugify a string in Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Copied from https://mudssrali.com/blog/slugify-a-string-in-elixir | |
| # and then modified to drop leading and trailing dashes. | |
| defmodule String do | |
| # 1. Convert a string to downcase | |
| # 2. Remove any leading and trailing spaces | |
| # 3. Convert graphemes to normal characters (e.g. á, é) | |
| # 4. Replace non-alphanumeric characters with an empty string | |
| # 5. Replace multiple spaces or dashes with a single dash | |
| # 6. Remove any leading and trailing dashes | |
| 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) | |
| |> String.replace(~r/-$|^-/, "", global: true) | |
| end | |
| def slugify(_), do: "" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment