Reading history

JavaScript URL and URLSearchParams: Read and Build Web Addresses

6 min read 1 views

Parse web addresses with the URL class, read and edit query strings with URLSearchParams, encode values correctly and keep filters in the address bar.

Web addresses carry a lot of information: the site, the page, and often settings such as ?page=2&sort=price. Splitting these strings by hand with split("?") and split("&") breaks on special characters and edge cases. JavaScript has two built-in tools that do it correctly: the URL class, for whole addresses, and URLSearchParams, for the query string. Both work in browsers and in Node.js.

In this lesson you will learn

  • The parts of a URL and how to read them
  • Resolving relative links against a base address
  • Reading, adding and removing query parameters
  • Building links with correct encoding
  • Updating the browser’s address bar for filters and search

You should know strings, objects and error handling.

The URL Class

"use strict";
// new URL() splits a web address into its parts
const url = new URL("https://shop.example.com:8080/books/science?class=9&sort=price#reviews");
console.log("protocol:", url.protocol);
console.log("hostname:", url.hostname);
console.log("port:    ", url.port);
console.log("pathname:", url.pathname);
console.log("search:  ", url.search);
console.log("hash:    ", url.hash);
console.log("origin:  ", url.origin);

// Relative links are resolved against a base URL
const page = new URL("../maths/algebra.html", "https://school.example.com/notes/physics/motion.html");
console.log(page.href);

// The parts can be changed, and href updates automatically
url.pathname = "/books/maths";
url.hash = "";
console.log(url.href);

// An invalid address throws a TypeError, so check first or use try/catch
console.log(URL.canParse("not a url"), URL.canParse("https://example.com"));
try {
  new URL("www.example.com");          // missing "https://"
} catch (err) {
  console.log(err.name + ": invalid URL");
}

Output

protocol: https:
hostname: shop.example.com
port:     8080
pathname: /books/science
search:   ?class=9&sort=price
hash:     #reviews
origin:   https://shop.example.com:8080
https://school.example.com/notes/maths/algebra.html
https://shop.example.com:8080/books/maths?class=9&sort=price
false true
TypeError: invalid URL
  • new URL(text) parses an address into named parts: protocol, hostname, port, pathname, search (the query, including ?) and hash (including #). origin combines protocol, host and port.
  • With a second argument, the first is treated as relative to it. ../ goes up one folder, exactly as in an HTML link.
  • Parts can be assigned, and href, the full address, updates to match.
  • An invalid address throws a TypeError. URL.canParse() checks first without throwing. Note that “www.example.com” is not a full URL: it lacks the protocol.

URLSearchParams

"use strict";
// URLSearchParams reads and builds the ?key=value part of a URL
const params = new URLSearchParams("?class=9&subject=physics&subject=chemistry&page=2");

console.log(params.get("class"));            // first value as a string
console.log(params.getAll("subject"));       // every value for a repeated key
console.log(params.has("sort"), params.get("sort"));   // missing key: false, null
console.log(Number(params.get("page")) + 1); // values are strings: convert numbers

// Change the parameters
params.set("page", "3");                     // replace
params.append("subject", "biology");         // add another value
params.delete("class");
console.log(params.toString());

// Loop over every pair
for (const [key, value] of params) {
  console.log(" ", key, "=", value);
}

// Building a search link safely: spaces and symbols are encoded for you
const search = new URL("https://example.com/search");
search.searchParams.set("q", "Newton's laws & motion");
search.searchParams.set("lang", "bn");
console.log(search.href);

// Turn the parameters into a plain object
console.log(Object.fromEntries(new URLSearchParams("name=Rina&roll=7")));

Output

9
[ 'physics', 'chemistry' ]
false null
3
subject=physics&subject=chemistry&page=3&subject=biology
  subject = physics
  subject = chemistry
  page = 3
  subject = biology
https://example.com/search?q=Newton%27s+laws+%26+motion&lang=bn
{ name: 'Rina', roll: '7' }
  • get(key) returns the first value as a string, or null if the key is missing. Convert numbers yourself with Number().
  • A key can appear several times, as subject does. getAll returns every value in an array.
  • set replaces all values of a key, append adds another, and delete removes the key. toString() produces the query string without the ?.
  • The object can be looped with for...of, giving [key, value] pairs, and Object.fromEntries turns it into a plain object (keeping one value per key).
  • Every URL has a searchParams property. Setting values through it encodes special characters automatically: the apostrophe became %27, the ampersand %26 and spaces +.

In the Browser

The current page’s address is available as a URL object, so reading and changing filters is short and safe:

// On https://shop.example.com/books?class=9
const url = new URL(location.href);
const cls = url.searchParams.get("class");          // "9"

// Change the address bar without reloading the page
url.searchParams.set("sort", "price");
history.replaceState(null, "", url);                // or pushState to add a history entry

Keeping filters in the URL means users can bookmark or share the exact view they are looking at. To read data from a form, new URLSearchParams(new FormData(form)) converts the form fields directly.

Encoding Functions

ToolUse for
URLSearchParams / url.searchParamsQuery strings: the best choice
encodeURIComponent(text)One value placed in a URL by hand, such as a path segment
encodeURI(text)A whole URL with unusual characters; it leaves / ? & # alone
decodeURIComponent(text)Turning %20-style codes back into characters

Common Mistakes

  1. Joining strings such as "?q=" + text without encoding, which breaks when the text contains &, # or spaces.
  2. Treating parameter values as numbers. They are always strings.
  3. Forgetting the protocol, so new URL("example.com") throws.
  4. Trusting URL parameters. Anyone can edit them, so validate them before use.

Practice Exercises

Exercise 1. From "https://example.com/watch?v=abc123&t=90", print the video id and the start time as a number.

Show answer
const u = new URL("https://example.com/watch?v=abc123&t=90");
console.log(u.searchParams.get("v"));            // "abc123"
console.log(Number(u.searchParams.get("t")));    // 90

Exercise 2. Write pageLink(n) that returns the current search page URL with page set to n, keeping all other parameters.

Show answer
function pageLink(n) {
  const url = new URL(location.href);
  url.searchParams.set("page", String(n));
  return url.href;
}

Frequently Asked Questions

Why is a space sometimes + and sometimes %20?

In query strings, URLSearchParams encodes a space as +, following the HTML form format. encodeURIComponent uses %20. Both decode back to a space when read with the matching tool.

Is the hash part sent to the server?

No. Everything after # stays in the browser. It is used for jumping to a section of the page or by single-page apps, so do not put information the server needs there.

Summary

  • new URL() splits an address into parts and resolves relative links.
  • URLSearchParams reads and edits the query string; values are strings.
  • Use searchParams.set to build links with correct encoding.
  • Combine with history.replaceState to keep filters in the address bar.

Next: Getters and Setters.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *