DEV Community

Dwayne Crooks
Dwayne Crooks

Posted on

What's the equivalent of encodeURIComponent in Elm?

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
Enter fullscreen mode Exit fullscreen mode

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)
    ]
Enter fullscreen mode Exit fullscreen mode

And that's exactly what I wanted.

Summary

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.

Oldest comments (2)

Collapse
 
michaelsnowden profile image
Michael Snowden

God bless you

Collapse
 
backnext321 profile image
backnext

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