DEV Community

Michael Burrows
Michael Burrows

Posted on • Edited on • Originally published at michaelburrows.xyz

7 1

Get the domain name from a string containing a URL in JavaScript

Parsing URL’s is a common task when developing web applications.

Fortunately JavaScript’s URL API makes it easy to read and modify URL’s without the need for REGEX.

First let’s create a string with our URL (Note: If the URL isn’t correctly structured you’ll get an error).

const url = 'https://www.michaelburrows.xyz/blog?search=hello&world';
Enter fullscreen mode Exit fullscreen mode

Next we create a URL object using the new URL() constructor.

let domain = (new URL(url));
Enter fullscreen mode Exit fullscreen mode

With the object created there are a number of properties we can access.

We’re interested in the hostname property which returns a string containing the domain name.

domain = domain.hostname;
console.log(domain); //www.michaelburrows.xyz
Enter fullscreen mode Exit fullscreen mode

If you require a naked domain (without the www) it can be removed using the replace() method.

domain = domain.hostname.replace('www.','');
console.log(domain); //michaelburrows.xyz
Enter fullscreen mode Exit fullscreen mode

Alternatively the code can be written as follows:

const url = 'https://www.michaelburrows.xyz/blog?search=hello&world';
const domain = (new URL(url)).hostname.replace('www.','');
Enter fullscreen mode Exit fullscreen mode

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay