Parsing URLs in JavaScript: Extracting Hostname and Path
When working with URLs in JavaScript, it's often necessary to extract specific components from the string representation. In this case, the goal is to parse a URL into its constituent parts, including the hostname (e.g., "example.com") and the path (e.g., "/aa/bb").
Modern Solution
The modern and standardized approach to URL parsing in JavaScript is through the use of the URL constructor. Consider the following example:
let a = new URL("http://example.com/aa/bb/");
This constructor returns an object with the following properties:
Note:
let a = new URL("/aa/bb/", location);
Legacy Options
Considerations
The above is the detailed content of How Can I Efficiently Parse URLs in JavaScript to Extract Hostname and Path?. For more information, please follow other related articles on the PHP Chinese website!