How to replace accented letters with ASCII letters?

If anyone stumbles upon this issue like I did, it might not be clear right away but at the moment it is doable to slugify a string using only string functions mostly discussed here: String.normalize(:nfd) would split the string into separate characters so that accents can be removed and ASCII parts remain leaving us with a reasonable slug (not a grammatically correct transcriptions but the ASCII parts of the special chars).

Here is a changeset function I came up with:

defp normalize_slug(changeset) do
  slug =
    changeset
    |> get_field(:slug)
    |> String.normalize(:nfd)
    |> String.downcase()
    |> String.replace(~r/[^a-z-\s]/u, "") 
    |> String.replace(~r/\s/, "-")

    put_change(changeset, :slug, slug)
end

Few tests from above:

Hubert Łępicki > hubert-epicki
árboles más grandes > arboles-mas-grandes
Übel wütet der Gürtelwürger > ubel-wutet-der-gurtelwurger

3 Likes