CodeBlanks Logo Icon CodeBlanks

URL properties

Learn URL.pathname, hostname and port properties.

pathname, hostname, port

You access a URL object's address components through properties. pathname gives the path, hostname the server name, port the port.

Example: for new URL("https://example.com:8080/path/to/page"), pathname is "/path/to/page", hostname is "example.com", port is "8080". If port is empty the default is used (443 for https, 80 for http); then url.port gives an empty string. hostname gives only the name; host gives name+port ("example.com:8080"). In routing, pathname is the most used property; frameworks like Express parse it automatically.

protocol, hash, origin

Other properties: protocol gives the protocol ("https:"), hash the anchor ("#section"), origin the protocol+host+port combination.

Example: for new URL("https://example.com:8080/path?q=1#section"), protocol is "https:", hash is "#section", origin is "https://example.com:8080". protocol ends with a colon; be careful when comparing. hash is only for in-page position in the browser; the server does not see it. origin is critical in CORS (cross-origin) checks; it compares whether two URLs come from the same origin. In this lesson's exercise we print pathname, hostname and port separately.

Practice Print URL components separately

Create a URL with const url = new URL("https://example.com:8080/path/to/page?q=1");. Print three components on separate lines with console.log(url.pathname), console.log(url.hostname) and console.log(url.port).

Starter code

index.js
// Create a URL
// write here

// Print pathname, hostname, port
// write here

Sample solution

index.js
const url = new URL("https://example.com:8080/path/to/page?q=1");
console.log(url.pathname);
console.log(url.hostname);
console.log(url.port);

Expected output

/path/to/page
example.com
8080

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each property to its value

Term Meaning
pathname /path/to/page
hostname example.com
port 8080
host example.com:8080

2 What does new URL("https://example.com:8080/x").port give?

index.js
new URL("https://example.com:8080/x").port
  • "443"
  • "80"
  • ""
  • "8080" Correct answer

Explanation: 8080 is explicit; the port property gives it.

3 Complete the pathname access

Question
const yol = url.____;
Answer
const yol = url.pathname;

Explanation: Write const yol = url.pathname;.

All lessons in Intermediate