What's the equivalent of encodeURIComponent in Elm?

dwayne profile image Dwayne Crooks ・2 min read

I was building a random quote machine application in Elm and needed to create a tweet web intent URL.

A tweet web intent makes it easy to compose and post a Tweet from a link.

Suppose you want to create a tweet web intent URL for the following quote:

Less mental clutter means more mental resources available for deep thinking. ~ Cal Newport, Deep Work: Rules for Focused Success in a Distracted World

In JavaScript

You can do the following:

content = 'Less mental clutter means more mental resources available for deep thinking.'
author = 'Cal Newport'

text = encodeURIComponent('"' + content + '" ~ ' + author)
url = 'https://twitter.com/intent/tweet?hashtags=quotes&text=' + text

To see what is supposed to happen, click here.

I use encodeURIComponent because the text parameter requires a URL-encoded string.

In Elm (0.19)

It took me a while but I finally found what I needed by using Elm Search.

N.B. To get to Elm Search you can go to Elm Packages and click the "Fancy Search" link under "Resources". That's how I found it.

The function lives in the elm/url package and is called percentEncode. It gives you the same behaviour as JavaScript's encodeURIComponent function.

However, its documentation advises you to use Url.Builder instead.

After reading the documentation you end up with something like the following:

import Url.Builder exposing (crossOrigin, string)

content = "Less mental clutter means more mental resources available for deep thinking."
author = "Cal Newport"

url =
  crossOrigin "https://twitter.com"
    [ "intent", "tweet" ]
    [ string "hashtags" "quotes"
    , string "text" ("\"" ++ content ++ "\" ~ " ++ author)

And that's exactly what I wanted.


In Elm, the equivalent of encodeURIComponent is called percentEncode and it can be found in the elm/url package. But, it should only be used for extremely custom cases. There's Url.Builder, which abstracts away the URL encoding bits among other things, and it's what you want to use to create your URLs.

Posted on Jun 21 '19 by:

dwayne profile

Dwayne Crooks


A full stack web developer who has an interest in programming language theory, interpreters, compilers and type theory. I enjoy programming with Elm and Haskell in my free time.


markdown guide

Can I activate Google Duo on android and make contact with 1 specific contact this way (with javascript)?