Extract the domain from a full URL using JavaScript?

suparman21 asked this question 8 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:


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