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.

Summary