🐥 Creating relative URLs from absolute URLs in Elixir
yellowduck.be·6d
🕷️Web Crawling
Preview
Report Post

230 words, 2 min read

When working with redirects, internal links, or LiveView navigation, you often want to turn an absolute URL into a relative one. Given a URL like:

https://example.com/some/path?page=2#section

the goal is to end up with:

/some/path?page=2#section

The non-idiomatic approach

A common first attempt is to manually concatenate path, query, and fragment after parsing the URL. While this works, it pushes URL semantics into string logic and is easy to get wrong.

Elixir’s standard library gives us a cleaner option.

The idiomatic solution using URI

The URI module is designed so that parsing and serialization are inverse operations. The trick is to parse the URL, drop the parts you don’t need, and convert it back to a string.

url = "https:...

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help