To extract the domain name from a URL in JavaScript, you can use the URL object. Here’s an example:
const url = new URL(“https://www.example.com/path?query=123”);
const domain = url.hostname;
console.log(domain); // Outputs: “www.example.com”
The URL object parses the URL and provides access to its components, such as hostname, protocol, and pathname. The hostname property returns the domain name, including subdomains. If you want only the main domain without subdomains, you’ll need additional processing, such as splitting the hostname by . and extracting the last two parts (e.g., example.com). This method ensures accurate parsing of valid URLs.