Home >Web Front-end >JS Tutorial >How to Extract Hostname and Path from a URL in JavaScript?

How to Extract Hostname and Path from a URL in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 17:07:10204browse

How to Extract Hostname and Path from a URL in JavaScript?

Parsing URLs in JavaScript: Extracting Hostname and Path

To dissect a URL into its hostname and path, a common requirement in web development, JavaScript offers several approaches.

1. Using the URL Object

Introduced in modern browsers and Node.js, the URL object provides direct access to URL properties, including hostname and pathname.

let url = new URL("http://example.com/aa/bb/");
console.log("Hostname: " + url.hostname);
console.log("Pathname: " + url.pathname);

2. Regular Expression Matching

For scenarios where direct URL parsing isn't available, regular expressions can be used to extract hostname and path.

let regex = /^(?:https?:\/\/)?(.*?)(?:\/.*)?$/;
let match = "http://example.com/aa/bb/".match(regex);
console.log("Hostname: " + match[1]);
console.log("Pathname: " + match[2]);

3. DOM Parsing

In older browsers, creating an HTML anchor element () and accessing its properties can also be used:

let a = document.createElement("a");
a.href = "http://example.com/aa/bb/";
console.log("Hostname: " + a.hostname);
console.log("Pathname: " + a.pathname);

Remember that hostname represents the domain without the port, while host includes both.

The above is the detailed content of How to Extract Hostname and Path from a URL in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn