Home >Web Front-end >JS Tutorial >How Can I Extract the Hostname and Path from a URL in JavaScript?
Parsing URL into Hostname and Path in JavaScript
To process a URL string into an object where you can access the hostname and pathname as desired, you can utilize modern solutions or alternative methods.
Modern Approach with URL Object:
The most straightforward solution is to use the URL constructor. It creates an instance of the URL object that provides the properties hostname and pathname. For example:
const a = new URL("http://example.com/aa/bb/"); console.log(a.hostname); // "example.com" console.log(a.pathname); // "/aa/bb"
Note that hostname contains only the domain, excluding any port information. For both domain and port, you can use host instead.
Alternative Approaches:
If the modern approach is not available, you can consider these alternative methods:
Conclusion:
The modern solution with the URL constructor is the preferred and recommended method for parsing a URL into hostname and pathname in JavaScript.
The above is the detailed content of How Can I Extract the Hostname and Path from a URL in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!