Introduction
The Node.js URL module practice questions provides tools for creating, reading, and modifying URLs in Node.js applications. It is especially useful when working with web addresses, query parameters, paths, protocols, and search values. In this chapter, you will practice the modern WHATWG URL API with simple examples. These questions start with basic URL handling and gradually move toward practical tasks such as reading and updating query parameters.
Question 1: How do you create a URL object in Node.js?
Problem
Create a URL object for a website and display it.
Solution
const { URL } = require("url");
const website = new URL("https://example.com");
console.log(website);
Output
The console representation can vary slightly by Node.js version, but it represents:
URL {
href: 'https://example.com/',
...
}
Step-by-Step Explanation
- Import the
URLclass from the built-inurlmodule. - Create a new
URLobject. - Pass the complete URL as a string.
- Node.js parses the URL and stores its different parts.
- Display the URL object.
Important Point
Node.js provides the URL class globally in modern versions, but importing it from the url module is useful for clearly learning where the API comes from.
Question 2: How do you get the protocol from a URL?
Problem
Find the protocol of a website URL.
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/about"
);
console.log(website.protocol);
Output
https:
Step-by-Step Explanation
- Create a URL object.
- Store the website URL.
- Access the
protocolproperty. - Node.js returns the protocol, including the colon.
For example:
https://example.com
has:
https:
as its protocol.
Question 3: How do you get the hostname from a URL?
Problem
Extract the hostname from this URL:
https://www.example.com/products
Solution
const { URL } = require("url");
const website = new URL(
"https://www.example.com/products"
);
console.log(website.hostname);
Output
www.example.com
Step-by-Step Explanation
- Create a URL object.
- Pass the website URL.
- Access
website.hostname. - Node.js returns only the hostname.
The hostname is:
www.example.com
It does not include the protocol or path.
Question 4: How do you get the pathname from a URL?
Problem
Extract the path from this URL:
https://example.com/products/mobile/phones
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/products/mobile/phones"
);
console.log(website.pathname);
Output
/products/mobile/phones
Step-by-Step Explanation
- Create a URL object.
- Pass the complete URL.
- Access the
pathnameproperty. - Node.js returns the path portion.
- The result starts with
/.
For:
https://example.com/products
the pathname is:
/products
Question 5: How do you get query parameters from a URL?
Problem
Read the name and age values from this URL:
https://example.com/profile?name=Riya&age=18
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/profile?name=Riya&age=18"
);
const name = website.searchParams.get("name");
const age = website.searchParams.get("age");
console.log("Name:", name);
console.log("Age:", age);
Output
Name: Riya
Age: 18
Step-by-Step Explanation
- Create a URL object.
- The query string appears after
?. website.searchParamsprovides access to query parameters.- Use
.get("name")to retrieve the name. - Use
.get("age")to retrieve the age. - Display both values.
The URL contains:
?name=Riya&age=18
Here:
nameis a parameter.Riyais its value.ageis a parameter.18is its value.
Question 6: How do you add a query parameter to a URL?
Problem
Add course=Node.js to an existing URL.
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/students"
);
website.searchParams.set(
"course",
"Node.js"
);
console.log(website.href);
Output
https://example.com/students?course=Node.js
Step-by-Step Explanation
- Create a URL object.
- Use
searchParams.set(). - The first argument is the parameter name.
- The second argument is its value.
- Node.js adds the query parameter.
- Use
hrefto get the complete updated URL.
Question 7: How do you update an existing query parameter?
Problem
Change the page value from 1 to 2.
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/products?page=1"
);
website.searchParams.set("page", "2");
console.log(website.href);
Output
https://example.com/products?page=2
Step-by-Step Explanation
- Create the URL.
- The URL already contains a
pageparameter. - Use
searchParams.set(). - Specify the parameter name as
"page". - Provide the new value
"2". - Display the updated URL.
set() creates the parameter if it does not exist and replaces its value if it already exists.
Question 8: How do you delete a query parameter?
Problem
Remove the category parameter from this URL:
https://example.com/products?category=mobile&page=2
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/products?category=mobile&page=2"
);
website.searchParams.delete("category");
console.log(website.href);
Output
https://example.com/products?page=2
Step-by-Step Explanation
- Create the URL object.
- Access
searchParams. - Use
.delete(). - Provide the parameter you want to remove.
categoryis removed.- The
pageparameter remains.
Question 9: How do you check whether a query parameter exists?
Problem
Check whether the URL contains a username query parameter.
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/login?username=Riya"
);
if (website.searchParams.has("username")) {
console.log("Username parameter exists.");
} else {
console.log("Username parameter does not exist.");
}
Output
Username parameter exists.
Step-by-Step Explanation
- Create the URL object.
- Access
searchParams. - Use
.has("username"). - The method returns
truewhen the parameter exists. - The
ifstatement displays the appropriate message.
For example:
website.searchParams.has("email");
would return false if the URL does not contain an email parameter.
Question 10: How do you build a URL dynamically using multiple query parameters?
Problem
Create a product search URL using:
- Product = laptop
- Category = electronics
- Page = 2
- Sort = price
Solution
const { URL } = require("url");
const website = new URL(
"https://example.com/products"
);
website.searchParams.set(
"product",
"laptop"
);
website.searchParams.set(
"category",
"electronics"
);
website.searchParams.set(
"page",
"2"
);
website.searchParams.set(
"sort",
"price"
);
console.log(website.href);
Output
https://example.com/products?product=laptop&category=electronics&page=2&sort=price
Step-by-Step Explanation
- Create the base URL.
- Add the
productparameter. - Add the
categoryparameter. - Add the
pageparameter. - Add the
sortparameter. - Use
website.hrefto get the complete URL. - Node.js automatically handles the query-string formatting.
This technique is useful when creating search URLs, filtering URLs, pagination links, and API request URLs.
Key Takeaways
- Node.js provides a built-in
urlmodule. - The modern
URLclass makes URL handling easier. - You can import it using
const { URL } = require("url"). url.protocolreturns the URL protocol.url.hostnamereturns the hostname.url.pathnamereturns the path.url.hrefreturns the complete URL as a string.url.searchParamsprovides access to query parameters.searchParams.get()reads a parameter value.searchParams.set()creates or updates a parameter.searchParams.delete()removes a parameter.searchParams.has()checks whether a parameter exists.- Query parameters are commonly used for searches, filters, pagination, and API requests.
- The
URLAPI automatically handles URL encoding when query parameters contain special characters.
FAQs
1. What is the URL module in Node.js?
The URL module is a built-in Node.js module that provides tools for parsing, creating, and modifying URLs.
A common way to use the modern URL API is:
const { URL } = require("url");
2. Do I need to install the URL module?
No. The url module is included with Node.js.
You can use:
const { URL } = require("url");
without installing an external package.
3. How do I get the hostname from a URL?
Create a URL object and access its hostname property:
const { URL } = require("url");
const website = new URL(
"https://www.example.com/products"
);
console.log(website.hostname);
Output:
www.example.com
4. How do I get query parameters in Node.js?
Use searchParams.get():
const { URL } = require("url");
const website = new URL(
"https://example.com/?name=Riya"
);
console.log(
website.searchParams.get("name")
);
Output:
Riya
5. How do I add a query parameter to a URL?
Use searchParams.set():
website.searchParams.set(
"page",
"2"
);
For example:
https://example.com/products?page=2
6. How do I remove a query parameter from a URL?
Use searchParams.delete():
website.searchParams.delete(
"page"
);
The specified parameter will be removed from the URL.
7. What is the difference between hostname and pathname?
hostname identifies the website host:
example.com
pathname identifies the path:
/products/mobile
For this URL:
https://example.com/products/mobile
the hostname is:
example.com
and the pathname is:
/products/mobile
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
