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

How to Parse a URL into Hostname and Path in JavaScript?

Linda Hamilton
Release: 2024-12-09 02:11:09
Original
835 people have browsed it

How to Parse a URL into Hostname and Path in JavaScript?

Parse URL into Hostname and Path in JavaScript

If you have a string containing a URL, it can be useful to break it into its components, such as the hostname and the path. In JavaScript, there are a few ways to achieve this.

Modern Approach:

The most modern approach is to use the URL constructor:

new URL("http://example.com/aa/bb/")
Copy after login

This returns an object with properties for hostname and pathname, among others like port and searchParams.

Note:

  • host property contains both hostname and port, while hostname only includes the domain.
  • If the given URL is relative, provide a base URL as the second argument to the constructor, such as:
new URL("/aa/bb/", location)
Copy after login

The above is the detailed content of How to Parse a URL into Hostname and Path 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