Saturday, January 11, 2025
HomeProgrammingHow to get domain name from URL in JavaScript

How to get domain name from URL in JavaScript

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x