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.comWithout www
Remove the prefix with replace():
const host = new URL('https://www.example.com').hostname.replace(/^www\./, '');
console.log(host);Output:
example.comFrom 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.orgCommon 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.comFunctions 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.