Links in a chain, image made with DiffusionBee

How to Remove the Domain Name from a URL with JavaScript

I needed to remove the domain name from a URL for use in a link, as the only part of the URL I needed was the path. I knew, I had to use a regular expression, but regex isn't exactly my favourite discipline. As ever so often, I found the answer on StackOverflow.

For any arbitrary URL, assuming that the variable url contains your URL, you can do:

url = url.replace(/^.*\/\/[^\/]+/, '')

This article was updated on 7 February 2023

Morten Bech

👋 Hi! I am a frontend web developer, designer, sparetime illustrator, librarian, husband, and father of two. 🤖 I work with frontend web development, UI design, and sometimes web graphics at a local TV station in the western part of Denmark, called TV MIDTVEST. 🛠️ Tools of the trade: VueJS, Nuxt, Tailwind, HTML, CSS, SCSS, JavaScript, Photoshop, Illustrator, Adobe XD, etc.

Comments