DEV Community

Cover image for URL [Slug Generator] With Elixir
Anthony Gonzalez
Anthony Gonzalez

Posted on • Updated on • Originally published at


URL [Slug Generator] With Elixir



Learn how to build a human-readable, search engine-friendly URL slugs generator with Elixir.

Step 1:

Create a new Elixir project by going to the command line and typing the following in your desired directory:

$ mix new slug_generator && cd slug_generator

Step 2:

Open your test file test/slug_generator_test.exs, remove the autogenerated test and add the following test:

  test "generates slug" do
    s = "[\"Pattern\", \"Matching\", \"In\", \"Elixir\"] = [a, b, c, d]"

    assert "pattern-matching-in-elixir-a-b-c-d" = SlugGenerator.create(s)

  test "generates simple slug" do
    s = "My slug generator & simple test "

    assert "my-slug-generator-and-simple-test" = SlugGenerator.create(s)
Enter fullscreen mode Exit fullscreen mode

Watch your tests fail by going to the command line and running the test by typing mix test.

Step 3:

Let's make our test pass by opening our main project file lib/slug_generator.ex, remove the autogenerated hello world function and add the following:

  def create(string) do
    |> String.downcase()
    |> String.replace(~r/[^a-zA-Z0-9 &]/, "")
    |> String.replace("&", "and")
    |> String.split()
    |> Enum.join("-")
Enter fullscreen mode Exit fullscreen mode

Go back to the command line and watch your tests pass with no failures by typing mix test.

Code Breakdown


Makes everything lowercase.

String.replace(subject, pattern, replacement)

We use it twice, the first is used with a regular expression as a pattern to replace everything that is not alphanumeric or the & symbol in the string with nothing or an empty string. The second time used with the & symbol as a pattern to get replaced with and.


Returns a list of substrings ignoring whitespace.

Enum.join(list, joiner)

Joins the list of substrings with the - symbol and returns a string.


That's a short and sweet way to build a URL slug generator with Elixir, using the useful String module combined with the Enum module. You could get way fancier and add more functionality but that should do it for this example tutorial. Thank you so much for your time, I really appreciate it.


Join The Elixir Army

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git