URL object
- Node.js course
- Intermediate
- Lesson 106/116
- 4 min
Learn to parse URLs with new URL().
The URL object
Node.js's built-in URL class parses an address and splits it into components. You create one with new URL("https://..."); no import is needed (it is global).
Example: const url = new URL("https://example.com:8080/path?q=hello");. This object has properties like href, protocol, hostname, port, pathname, search. An invalid address throws TypeError; so when building a URL from user input, a try/catch is a good habit. url.href gives the full address as a string; parsing and rejoining standardizes ordering. The URL object works the same in both server and browser code.
URL properties overview
Common properties of a URL object: href (full address), protocol (https:), hostname (example.com), port (8080), pathname (/path), search (?q=1), hash (#section).
Example: for new URL("https://example.com:8080/path?q=1#section"), protocol is "https:", hostname is "example.com", port is "8080", pathname is "/path", search is "?q=1", hash is "#section". origin combines protocol+host+port: "https://example.com:8080". These properties are both readable and writable; changing one updates href automatically. Properties are the topic of later lessons; here we only print href to see parsing works.
Practice Parse a URL and print href
Create a URL with const url = new URL("https://example.com:8080/path?q=merhaba");. Print the full address with console.log(url.href).
Starter code
// Create a URL object
// write here
// Print the full address
// write hereSample solution
const url = new URL("https://example.com:8080/path?q=merhaba");
console.log(url.href);Expected output
https://example.com:8080/path?q=merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does new URL() return?
const url = new URL("https://example.com");- Bir dize
- Bir URL nesnesi Correct answer
- A number
- Bir Promise
Explanation: new URL() returns a URL object.
2 Complete the URL construction
const url = new ____(adres);
const url = new URL(adres);
Explanation: new URL creates a URL object.
3 Match each piece to its role
| Term | Meaning |
|---|---|
new URL() |
Creates URL object |
href |
Full address |
protocol |
Protocol (https:) |
search |
Query string (?q=1) |