๐Ÿš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
๐ŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
JS MASTER CLASS /// MASTER THE ENGINE /// BUILD LOGIC /// ASYNC PATTERNS /// JS MASTER CLASS /// MASTER THE ENGINE ///

The URL API | JavaScript Tutorial - In-Depth Guide

Master the URL API: parsing and constructing URLs, reading and building query strings with URLSearchParams, and why manual string concatenation for URLs is error-prone.

โšก Total XP: 0|๐Ÿ’ป javascript XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

Does URLSearchParams correctly handle a query string with the same key appearing multiple times?


๐Ÿš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
๐ŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

The URL and URLSearchParams interfaces replace fragile, regex-based URL and query-string parsing with a robust, spec-compliant API built directly into the browser and Node.js.

1The URL API | JavaScript Tutorial - In-Depth Guide Part 1

The URL constructor parses a URL string into its components โ€” protocol, host, pathname, search, hash โ€” without any manual string splitting or regex.

โœ•
โ€”
+
const url = new URL('https://example.com:8080/path?query=1#hash');
url.hostname; // 'example.com'
url.pathname; // '/path'
url.hash;     // '#hash'
localhost:3000
๐Ÿ”—

Parsing URLs

2The URL API | JavaScript Tutorial - In-Depth Guide Part 2

URLSearchParams parses and builds query strings correctly, handling encoding/decoding and repeated parameter names automatically.

โœ•
โ€”
+
const params = new URLSearchParams('?tag=js&tag=web&page=2');
params.get('page');   // '2'
params.getAll('tag'); // ['js', 'web']
localhost:3000

URLSearchParams

3The URL API | JavaScript Tutorial - In-Depth Guide Part 3

A URL object's '.searchParams' property gives direct, live access to its query string as a URLSearchParams instance โ€” modifying it updates the URL automatically.

โœ•
โ€”
+
const url = new URL('https://example.com/search');
url.searchParams.set('q', 'javascript tutorials');
url.href; // 'https://example.com/search?q=javascript+tutorials'
localhost:3000

Building Query Strings

4The URL API | JavaScript Tutorial - In-Depth Guide Part 4

The URL constructor's second argument resolves a relative URL against a base URL, exactly like a browser resolves a relative link on a page.

โœ•
โ€”
+
new URL('../logo.png', 'https://example.com/blog/post-1/').href;
// 'https://example.com/logo.png'
localhost:3000

Resolving Relative URLs

5The URL API | JavaScript Tutorial - In-Depth Guide Part 5

Passing an invalid URL string to the URL constructor throws a TypeError immediately, which is a reliable way to validate URL input from users.

โœ•
โ€”
+
function isValidUrl(str) {
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
}
localhost:3000

Validating URLs

6Step-by-Step Breakdown

The URL constructor parses a URL string into its components โ€” protocol, host, pathname, search, hash โ€” without any manual string splitting or regex.

URLSearchParams parses and builds query strings correctly, handling encoding/decoding and repeated parameter names automatically.

Checkpoint: Does URLSearchParams correctly handle a query string with the same key appearing multiple times?

  • โ†’Yes, getAll() retrieves every value for that key
  • โ†’No, only the last occurrence is kept

A URL object's '.searchParams' property gives direct, live access to its query string as a URLSearchParams instance โ€” modifying it updates the URL automatically.

The URL constructor's second argument resolves a relative URL against a base URL, exactly like a browser resolves a relative link on a page.

Passing an invalid URL string to the URL constructor throws a TypeError immediately, which is a reliable way to validate URL input from users.

Checkpoint: What happens if you pass a malformed string to new URL(...)?

  • โ†’It throws a TypeError
  • โ†’It returns null

Next, we'll explore 'The History API'.

Level Up ๐Ÿš€

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Reflect Accessible Filter State in the URL for Shareable, Bookmarkable Views

Using URLSearchParams to encode active filters in the URL lets keyboard and screen reader users bookmark or share a specific filtered view, and lets the page restore that exact state (including any relevant focus or announcement) on load.

SEO Implications

  • 1

    Clean, Correctly-Encoded URLs Are More Crawlable and Shareable

    Search engines parse and index URLs; malformed query strings from manual concatenation (double-encoded characters, missing separators) can produce broken or duplicate-looking URLs that hurt crawl efficiency and canonicalization.

Best Practices

Use URL/URLSearchParams Instead of Manual String Concatenation for Query Strings

Manual concatenation is a common source of double-encoding bugs, missing "?"/"&" separators, and mishandling of special characters that URLSearchParams handles correctly by construction.

Validate User-Supplied URLs with the URL Constructor, Not a Custom Regex

A hand-written URL-validation regex is almost always incomplete or overly permissive; relying on the actual spec-compliant browser/Node parser is more robust.

Frequent Bugs

THE BUG

Manually building a query string with template literals, forgetting to encodeURIComponent() a value containing special characters like '&' or '#', corrupting the resulting URL.

THE FIX

Use URLSearchParams to build the query string instead, which handles encoding automatically and correctly for every value.

THE BUG

Assuming a relative URL like 'images/logo.png' can be safely string-concatenated onto a base URL, breaking when the base has its own path segments or query string.

THE FIX

Use `new URL(relativePath, baseUrl)` to correctly resolve the relative path according to standard URL resolution rules.

Real-World Examples

Building a Shareable Search Results URL

A search feature needed to reflect the current search query and filters in the URL, so results could be shared via a link and restored on page load.

function buildSearchUrl(baseUrl, { query, category, page }) {
  const url = new URL(baseUrl);
  url.searchParams.set('q', query);
  if (category) url.searchParams.set('category', category);
  url.searchParams.set('page', String(page));
  return url.toString();
}

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Manually concatenating query parameters without encoding

const params = new URLSearchParams({ q: 'a & b' }); params.toString(); // 'q=a+%26+b'

The Solution //

Use URLSearchParams to build query strings, which encodes values correctly by default.

Lesson Glossary

[01]URL Interface

A built-in object for parsing, constructing, and manipulating URLs.

Code Preview
new URL(str)

[02]URLSearchParams

A built-in interface for parsing and building query string parameters.

Code Preview
new URLSearchParams(str)

[03]searchParams

A URL object's live, linked URLSearchParams view of its query string.

Code Preview
url.searchParams

[04]Base URL Resolution

Resolving a relative URL against a base, like a browser resolves relative links.

Code Preview
new URL(rel, base)

[05]URL Encoding

Encoding special characters in a URL so they are transmitted correctly, handled automatically by URLSearchParams.

Code Preview
%20 for space

Continue Learning