Eleventy Filter to Turn a URL Into a Domain Name
For a new site I’m working on I needed to convert a URL https://howmanydaysuntilomloop.com/
into just the domain name howmanydaysuntilomloop.com
.
Originally I had a somewhat silly Liquid chain set up:
{{ url | remove: "https://" | remove: "http://" | remove: "www." | remove: "/" }}
After some digging on the internets I found a good tutorial on how to do it much simpler via JavaScript. Bonus: it also strips the path.
So I added the following to my eleventy.config.js
file:
eleventyConfig.addFilter("domainify", function(string) {
return new URL(string).hostname.replace('www.','');
});
And voilà, I can now use it as a regular filter inside my 11ty build:
{{ url | domainify }}