EthicsComputerCourses
Join training +91 90532 10052

URL & URLSearchParams API

HTML · Lesson 150 of 234 Advanced 10 min read Updated

By the end of this lesson you will be able to resolve any link against a base exactly as the browser does, build and edit query strings without string bugs, generate filter links for a product listing, choose the right encoding function and reject dangerous URLs typed by users.

What you should know first: Internal & External Links for how relative paths work, and Browser APIs: URL, History & More, which introduced the URL parts and basic URLSearchParams methods. This lesson builds on both. History API uses these objects all the time.

Why not just use strings?

A URL looks like simple text, so beginners glue it together with + and split it with split("?"). That breaks the moment a value contains a space, an &, a # or a Hindi word. The URL object uses the same parser as the browser's address bar, defined in the WHATWG URL Standard. If the browser would understand a link one way, URL gives you the same answer.

Think of a courier label: name, house number, street, city, PIN code. You would not write it as one long line and hope the courier guesses which part is the PIN. URL keeps each part in its own labelled box.

Resolving with a base

new URL(input, base) resolves input against base, using the same rules as <a href>. On a real page the base is usually location.href or document.baseURI.

JavaScript
const base = "https://meerastores.example/shop/sarees/";
for (const href of ["silk", "./silk?page=2", "../kurtas", "/offers", "?page=3", "#reviews", "//cdn.example/logo.svg"]) {
  console.log(href.padEnd(24), new URL(href, base).href);
}
console.log(new URL("silk", "https://meerastores.example/shop/sarees").href);
Output
silk                     https://meerastores.example/shop/sarees/silk
./silk?page=2            https://meerastores.example/shop/sarees/silk?page=2
../kurtas                https://meerastores.example/shop/kurtas
/offers                  https://meerastores.example/offers
?page=3                  https://meerastores.example/shop/sarees/?page=3
#reviews                 https://meerastores.example/shop/sarees/#reviews
//cdn.example/logo.svg   https://cdn.example/logo.svg
https://meerastores.example/shop/silk

Look at the last line. Without the trailing slash, sarees is treated as a file name, so silk replaces it. This is the same trailing-slash trap you met with HTML paths. A link starting with // is protocol-relative: it keeps the scheme (https:) and changes the host.

The parser also normalises the URL: it lowercases the scheme and host, drops the default port, resolves .. and encodes spaces.

JavaScript
const u = new URL("HTTPS://MeeraStores.Example:443/shop/../offers/diwali sale?q=red saree#top");
console.log(u.href);
console.log(u.port === "", u.origin);
u.pathname = "/offers/holi";
u.hash = "";
u.searchParams.set("q", "gulal");
console.log(u.href);
Output
https://meerastores.example/offers/diwali%20sale?q=red%20saree#top
true https://meerastores.example
https://meerastores.example/offers/holi?q=gulal

Every part is also a setter: assign to pathname, hash, search or hostname, and href updates. port is an empty string when the port is the default for the scheme (443 for HTTPS, 80 for HTTP).

Parsing without exceptions

new URL() throws a TypeError when the input cannot be parsed. Two static methods avoid try...catch:

  • URL.canParse(input, base) returns true or false (Baseline 2023).
  • URL.parse(input, base) returns a URL object or null (Baseline 2024: Chrome 126, Firefox 126, Safari 18).
JavaScript
console.log(URL.parse("/offers"));
console.log(URL.parse("/offers", "https://meerastores.example/")?.pathname);
console.log(URL.canParse("meerastores.example/offers"));
Output
null
/offers
false

"/offers" alone has no scheme or host, so it needs a base. "meerastores.example/offers" is not a URL either: without https:// the parser cannot know that the first part is a host.

Step 1: a URL inspector

Type any URL, or a relative path, and see every part. The base box shows how relative input is resolved.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>URL inspector</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    input { width: 100%; max-width: 32rem; }
    table { border-collapse: collapse; margin-top: 12px; }
    th, td { border: 1px solid #ccc; padding: 4px 8px; text-align: left; font-family: monospace; }
  </style>
</head>
<body>
  <p><label for="input">URL or path</label><br>
    <input id="input" value="../kurtas/cotton?size=M&amp;size=L#reviews"></p>
  <p><label for="base">Base</label><br>
    <input id="base" value="https://meerastores.example/shop/sarees/silk"></p>
  <p id="result" role="status"></p>
  <table id="parts" hidden>
    <tbody></tbody>
  </table>

  <script>
    const fields = ["href", "origin", "protocol", "host", "hostname", "port", "pathname", "search", "hash", "searchParams"];

    function inspect() {
      const base = document.querySelector("#base").value.trim();
      const url = URL.parse(document.querySelector("#input").value.trim(), base || undefined);
      const table = document.querySelector("#parts");
      if (!url) {
        document.querySelector("#result").textContent = "This cannot be parsed. Is the base a full URL?";
        table.hidden = true;
        return;
      }
      document.querySelector("#result").textContent = "Parsed:";
      const rows = fields.map((name) => {
        const tr = document.createElement("tr");
        const th = document.createElement("th");
        const td = document.createElement("td");
        th.textContent = name;
        const value = name === "searchParams" ? JSON.stringify([...url.searchParams]) : url[name];
        td.textContent = value === "" ? "(empty)" : value;
        tr.append(th, td);
        return tr;
      });
      table.tBodies[0].replaceChildren(...rows);
      table.hidden = false;
    }

    document.querySelector("#input").addEventListener("input", inspect);
    document.querySelector("#base").addEventListener("input", inspect);
    inspect();
  </script>
</body>
</html>

With the starting values, href is https://meerastores.example/shop/kurtas/cotton?size=M&size=L#reviews, port is "(empty)" and searchParams shows [["size","M"],["size","L"]]. Clear the base and the message says it cannot be parsed. Then type a full URL such as https://rail.example:8080/pnr?no=4521 and every part fills in again.

URLSearchParams in depth

MethodWhat it does
get(name)First value, or null
getAll(name)Every value, as an array
set(name, value)Replaces all values of name with one value
append(name, value)Adds another value, keeping the old ones
delete(name) / delete(name, value)Removes all values, or only that one pair
has(name) / has(name, value)Checks for a name, or for one exact pair
sort()Sorts pairs by name, keeping the order of equal names
sizeNumber of pairs
toString()The encoded query string, without ?

The two-argument forms of delete() and has() and the size property are Baseline 2023. They are exactly what a multi-select filter needs.

Why sort()? ?brand=prestige&sort=price and ?sort=price&brand=prestige show the same products, but caches and search engines see two different URLs. Sorting before you build a link gives one canonical URL for each filter combination.

Meera's online store in Jaipur lists pressure cookers. Checkboxes pick brands (several allowed), a menu picks the sort order, and each active filter becomes a "chip" with a remove link. Every link is a real URL, so it can be shared, bookmarked and crawled.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Pressure cookers</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    fieldset { display: inline-block; margin-right: 12px; }
    #link { font-family: monospace; word-break: break-all; background: #eef; padding: 6px; }
    .chip { display: inline-block; background: #ffe0b2; border-radius: 12px; padding: 2px 10px; margin: 2px; }
  </style>
</head>
<body>
  <h1>Pressure cookers</h1>
  <form id="filters">
    <fieldset>
      <legend>Brand</legend>
      <label><input type="checkbox" name="brand" value="prestige"> Prestige</label>
      <label><input type="checkbox" name="brand" value="hawkins"> Hawkins</label>
      <label><input type="checkbox" name="brand" value="butterfly"> Butterfly</label>
    </fieldset>
    <label>Sort
      <select name="sort">
        <option value="">Relevance</option>
        <option value="price-asc">Price: low to high</option>
        <option value="rating">Rating</option>
      </select>
    </label>
  </form>
  <p>Shareable link:</p>
  <p id="link"></p>
  <p id="chips" aria-label="Active filters"></p>

  <script>
    const page = "https://meerastores.example/kitchen/pressure-cookers";   // location.href on a real site
    const form = document.querySelector("#filters");

    function buildUrl() {
      const url = new URL(page);
      for (const box of form.querySelectorAll("[name=brand]:checked")) {
        url.searchParams.append("brand", box.value);
      }
      if (form.sort.value) url.searchParams.set("sort", form.sort.value);
      url.searchParams.sort();               // one canonical URL per combination
      return url;
    }

    function render() {
      const url = buildUrl();
      document.querySelector("#link").textContent = url.href;
      const chips = [];
      for (const [name, value] of url.searchParams) {
        const without = new URL(url);
        without.searchParams.delete(name, value);   // remove only this one pair
        const a = document.createElement("a");
        a.className = "chip";
        a.href = without.href;
        a.textContent = `${name}: ${value} (remove)`;
        a.dataset.name = name;
        a.dataset.value = value;
        chips.push(a);
      }
      document.querySelector("#chips").replaceChildren(...chips);
    }

    // In this demo a chip click unticks the box instead of loading the link
    document.querySelector("#chips").addEventListener("click", (event) => {
      const chip = event.target.closest("a");
      if (!chip) return;
      event.preventDefault();
      if (chip.dataset.name === "sort") form.sort.value = "";
      else form.querySelector(`[name=brand][value="${chip.dataset.value}"]`).checked = false;
      render();
    });

    form.addEventListener("change", render);
    render();
  </script>
</body>
</html>

Tick Hawkins, then Prestige, and choose "Rating". The link becomes https://meerastores.example/kitchen/pressure-cookers?brand=prestige&brand=hawkins&sort=rating. The brands follow the checkbox order, not your click order, and sort() fixes the order of the names, so the same choice always gives the same link. Each chip's href is the same URL with only that pair deleted. Click the Prestige chip: the box unticks and the link loses only brand=prestige.

Encoding rules

Characters such as space, &, =, # and + have special meanings in a URL. Inside a value they must be percent-encoded: written as % and two hex digits. JavaScript has several tools, and they disagree slightly:

JavaScript
const value = "Tea & Coffee (Assam) 100% pure!";
console.log(encodeURIComponent(value));
console.log(new URLSearchParams({ q: value }).toString());
console.log(encodeURI("https://meerastores.example/search?q=tea & coffee"));

const p = new URLSearchParams("q=tea+%26+coffee&size=a%2Bb");
console.log(p.get("q"), "|", p.get("size"));
console.log(decodeURIComponent("tea+%26+coffee"));
Output
Tea%20%26%20Coffee%20(Assam)%20100%25%20pure!
q=Tea+%26+Coffee+%28Assam%29+100%25+pure%21
https://meerastores.example/search?q=tea%20&%20coffee
tea & coffee | a+b
tea+&+coffee
ToolSpace becomesUse it for
URLSearchParams / url.searchParams+Query strings: the normal choice
encodeURIComponent()%20One value placed in a path segment or a hash
encodeURI()%20A whole URL; it leaves &, =, ? and # alone

The third line shows why encodeURI() is dangerous for values: the & stays raw, so the server sees q=tea and a second, broken parameter. Also, decodeURIComponent() does not turn + into a space, but URLSearchParams does. Encode and decode with the same tool. Never encode a value twice, or % becomes %25 and the server sees %2520.

Validating URLs typed by users

Ananya's profile form has a "Your website" field, shown as a link on her public page. If you put any text into href, someone can enter javascript: followed by code, and the code runs for every visitor who clicks the link. That is a stored XSS attack. The fix is an allow-list: parse the URL and accept only the schemes you want.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Website field</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    li { margin: 4px 0; font-family: monospace; }
    .ok { color: #1b5e20; } .bad { color: #b71c1c; }
  </style>
</head>
<body>
  <label for="site">Your website</label>
  <input id="site" size="40" value="www.ananya-art.example">
  <button type="button" id="check">Check</button>
  <p id="preview" role="status"></p>
  <h2>Test inputs</h2>
  <ul id="tests"></ul>

  <script>
    function safeWebUrl(input) {
      let text = input.trim();
      if (text !== "" && !/^[a-z][a-z0-9+.-]*:/i.test(text)) text = "https://" + text;   // "www.x.com" -> https
      const url = URL.parse(text);
      if (!url) return { ok: false, reason: "not a valid URL" };
      if (url.protocol !== "https:" && url.protocol !== "http:") {
        return { ok: false, reason: `scheme ${url.protocol} is not allowed` };
      }
      if (url.username || url.password) return { ok: false, reason: "login details in URLs are not allowed" };
      return { ok: true, url };
    }

    function showLink(target, input) {
      const result = safeWebUrl(input);
      if (!result.ok) {
        target.className = "bad";
        target.textContent = `Rejected "${input}": ${result.reason}`;
        return;
      }
      const a = document.createElement("a");
      a.href = result.url.href;
      a.rel = "ugc nofollow noopener";
      a.target = "_blank";
      a.textContent = result.url.hostname;
      target.className = "ok";
      target.replaceChildren("Accepted: ", a);
    }

    document.querySelector("#check").addEventListener("click", () => {
      showLink(document.querySelector("#preview"), document.querySelector("#site").value);
    });

    const samples = ["https://ananya-art.example/gallery", "  JaVaScRiPt:alert(1)", "data:text/html,<h1>hi</h1>",
      "ftp://files.example/song.mp3", "https://admin:secret@bank.example", "http://", "www.kochi-cafe.example"];
    for (const s of samples) {
      const li = document.createElement("li");
      showLink(li, s);
      document.querySelector("#tests").append(li);
    }
  </script>
</body>
</html>

The test list shows two accepted links (ananya-art.example and www.kochi-cafe.example) and five rejections. The mixed-case JaVaScRiPt: with leading spaces is caught because the parser trims spaces and lowercases the scheme, so url.protocol is "javascript:". Checking with startsWith("http") on the raw text would be fooled by tricks like this. http:// alone is rejected because it is not a valid URL. Press Check to test your own input.

The rel="ugc nofollow" values tell search engines the link is user-generated content and not an endorsement. noopener stops the new tab from controlling your page.

Common mistakes

  • Building query strings with + and template literals. One & in a value breaks the URL. Use searchParams.
  • Forgetting the trailing slash on a base. new URL("silk", ".../sarees") drops sarees.
  • set() when you meant append(). The second brand filter replaces the first.
  • encodeURI() on a value. It leaves & and = unencoded.
  • Validating with startsWith("http"). Parse first, then compare url.protocol exactly.
  • Checking only in the browser. Repeat validation on the server.

Interview questions

1. What does the second argument of new URL() do?

It is the base URL that a relative input is resolved against, using the same rules as links in HTML. new URL("../kurtas", "https://shop.example/sarees/silk") gives https://shop.example/kurtas. Without a base, a relative input throws a TypeError.

2. What is the difference between URL.canParse() and URL.parse()?

canParse() only answers true or false. parse() returns the parsed URL object, or null instead of throwing. Both avoid try...catch; use parse() when you need the parts afterwards.

3. Why does encodeURIComponent() give %20 while URLSearchParams gives +?

URLSearchParams follows the application/x-www-form-urlencoded format used by HTML forms, where a space is +. encodeURIComponent() follows general URL percent-encoding. Servers decode both in query strings, but you must decode with the matching tool.

4. How do you safely accept a website URL from a user?

Parse it with URL.parse(), allow only http: and https: by comparing url.protocol, and reject anything else, including javascript: and data:. Repeat the check on the server and output the link with proper escaping.

5. Why call searchParams.sort() before building a link?

The same filters chosen in a different order would otherwise produce different URLs. Sorting gives one canonical URL per combination, which helps caching, analytics and search engines.

Key points

  • new URL(input, base) resolves links exactly like the browser; mind the trailing slash on the base.
  • URL parts are getters and setters; the parser normalises case, default ports, .. and spaces.
  • URL.parse() returns null and URL.canParse() returns false for bad input instead of throwing.
  • Use getAll(), append() and two-argument delete() for multi-value filters, and sort() for canonical links.
  • Query strings: URLSearchParams. Single path or hash values: encodeURIComponent(). Never encode twice.
  • Accept user URLs only after parsing and allowing http: and https:, in the browser and on the server.

Exercise

Build a train search link builder. The form has "From" and "To" text fields, a date field and checkboxes for classes (SL, 3A, 2A). On every change, build a URL for https://rail.example/search with from, to, date and one class parameter per ticked box, sorted, and show it as a link. Station names may contain spaces and &, such as "Mumbai & Thane". Also show a warning if "From" and "To" are the same, ignoring case and spaces.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Train search link</title>
</head>
<body>
  <form id="f">
    <label>From <input name="from" value="Pune"></label>
    <label>To <input name="to" value="Mumbai &amp; Thane"></label>
    <label>Date <input type="date" name="date" value="2026-12-20"></label>
    <label><input type="checkbox" name="class" value="SL"> SL</label>
    <label><input type="checkbox" name="class" value="3A" checked> 3A</label>
    <label><input type="checkbox" name="class" value="2A"> 2A</label>
  </form>
  <p><a id="link"></a></p>
  <p id="warn" role="alert"></p>
  <script>
    const form = document.querySelector("#f");
    function build() {
      const url = new URL("https://rail.example/search");
      for (const name of ["from", "to", "date"]) {
        const value = form[name].value.trim();
        if (value) url.searchParams.set(name, value);
      }
      for (const box of form.querySelectorAll("[name=class]:checked")) {
        url.searchParams.append("class", box.value);
      }
      url.searchParams.sort();
      const link = document.querySelector("#link");
      link.href = url.href;
      link.textContent = url.href;
      const same = (s) => s.toLowerCase().replace(/\s+/g, "");
      document.querySelector("#warn").textContent =
        form.from.value && same(form.from.value) === same(form.to.value) ? "From and To cannot be the same station." : "";
    }
    form.addEventListener("input", build);
    build();
  </script>
</body>
</html>

With the starting values the link is https://rail.example/search?class=3A&date=2026-12-20&from=Pune&to=Mumbai+%26+Thane. searchParams encodes the & as %26, and append() adds one class pair per ticked box.

Quick Quiz

1. What does new URL("silk", "https://shop.example/sarees").href return?

2. What does URL.parse("not a url") return?

3. A filter allows several sizes. Which method adds size=L without removing size=M?

4. A user enters JAVASCRIPT:alert(1) as their website. How does a safe check reject it?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call