Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get the domain from an email or a URL

Short answer

URL gives the host name in the hostname property:

const url = new URL('https://www.example.com/blog/post?id=5');
 
console.log(url.hostname);

Output:

www.example.com

Without www

Remove the prefix with replace():

const host = new URL('https://www.example.com').hostname.replace(/^www\./, '');
 
console.log(host);

Output:

example.com

From an email

The domain is everything after the last @:

const email = 'anna.smith@mail.example.org';
 
console.log(email.slice(email.lastIndexOf('@') + 1));

Output:

mail.example.org

Common mistake

An address without a protocol is not a valid URL, and new URL() throws an error. Add the protocol if it is missing:

const input = 'example.com/page';
const url = new URL(/^https?:\/\//.test(input) ? input : 'https://' + input);
 
console.log(url.hostname);

Output:

example.com

Functions used in this recipe

  • URL — Parses an address into parts and builds it back.
  • String.prototype.split — Splits a string into an array by a separator.

Thanks for reading!

Donate to the site — we work hard for you.