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
Linda HamiltonOriginal
2024-12-09 02:11:09832browse

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/")

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)

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!

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