Extract the domain from a full URL using JavaScript?

Answered
suparman21 asked this question 4 months ago
suparman21 on Jan 21 · Edited

In my JavaScript code, I need to take a full URL and figure what the domain name is.

For example, this URL:

https://chunkks.com/questions/221/how-to-use-the-lodash-npm-package-in-node-js

I would need to extract the chunkks.com domain name.

Thanks in advance for the help!

2 suggested answers
coderguy on Jan 30

Try this:

const url = "https://cloud.digitalocean.com/login"

const {hostname} = new URL(url) // "cloud.digitalocean.com
0 replies
moon_man41 on Jan 30

You can use a regular expression to achieve this:

const url = "https://youtube.com/watch?v=K4ZAPAjMnOw"

var match = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i)
var domain = match && match[1] // "youtube.com"
0 replies
Answered