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
Release: 2024-12-11 17:07:10
Original
216 people have browsed it

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);
Copy after login

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]);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template