JavaScript URLSearchParams: Share a Course Filter in a Link

Practical Web Development — Lesson 3 of 10 · Intermediate

A search box that resets after reload is frustrating when someone wants to share a filtered list. Store the public search term in the URL so a link can recreate the same view. This exercise uses URL, URLSearchParams and the History API without a framework. Run it from a local HTTP server so the page has a normal web origin.

Build the complete small example

<label for="query">Find a course</label>
<input id="query" type="search">
<p id="count" role="status"></p><ul id="courses"></ul>
<script>
const courses = ['HTML fundamentals', 'CSS layout', 'JavaScript DOM'];
const input = document.querySelector('#query');
const list = document.querySelector('#courses');
const count = document.querySelector('#count');
const initial = new URL(location.href);
input.value = (initial.searchParams.get('q') || '').slice(0, 100);
function render() {
  const term = input.value.trim().toLowerCase();
  const matches = courses.filter(name => name.toLowerCase().includes(term));
  list.replaceChildren(...matches.map(name => {
    const item = document.createElement('li');
    item.textContent = name;
    return item;
  }));
  count.textContent = matches.length + ' courses found';
}
input.addEventListener('input', () => {
  const url = new URL(location.href);
  const value = input.value.slice(0, 100);
  if (value) url.searchParams.set('q', value);
  else url.searchParams.delete('q');
  history.replaceState(null, '', url);
  render();
});
render();
</script>

Why use a URL object?

String concatenation easily breaks when a query contains an ampersand, a space or a question mark. Search parameters handle encoding. Starting from the current URL preserves other parameters and the fragment instead of silently deleting unrelated navigation state. The term is limited on initial load so a pasted URL cannot populate an arbitrarily long search field.

This demo changes the current history entry with replaceState. Typing ten characters therefore does not create ten Back-button stops. If your product has an explicit Apply filters action, pushState may be appropriate on that action, together with a popstate handler to restore the view when users navigate history.

Decide what belongs in a shareable URL

A public course search is a reasonable URL parameter. Passwords, tokens and private learner notes are not: URLs can appear in history, logs and shared messages. URL state is user input, not a source of authorization. A backend must still validate any parameters it uses.

Test the contract

  1. Search for CSS and reload. Only the CSS course should remain.
  2. Copy the URL into another tab and compare results.
  3. Clear the field and verify the q parameter disappears.
  4. Search for a term with no match; the count should be zero.
  5. Type special characters and verify they display as text, not markup.

Practice

Add a level parameter with an allowlist of beginner and intermediate. Unknown values should fall back to all levels. Keep the query and level independent so changing one does not erase the other. Document that fallback before implementing it.

Continue learning

Review our semantic HTML project, JavaScript course filter and course platform architecture.

Reference: Technical documentation for this lesson. Examples are learning exercises; test them in your environment.

Comments

Popular posts from this blog

What Is Multimedia? Examples and a Beginner Course Guide

Internet vs World Wide Web: HTML and Multimedia Explained

Video in Multimedia: Formats, Compression and Captions