Before this lesson

Understand URL paths, query parameters, fragments and DOM events.

What you will be able to do

Update query parameters without losing other state and distinguish navigation from history updates.

Understand the mechanism

A URL has distinct components that should not be edited by blindly appending punctuation. Use URL and searchParams. set replaces values while append permits duplicates; a single language state should use set.

Copy the current URL and change only the relevant parameter to preserve IDs, search and fragments. Let searchParams serialize Unicode and spaces rather than pre-encoding them. Encoding does not provide authorization or validate destinations.

Navigation loads a document; replaceState updates the address without requesting new server content, and pushState likewise does not render automatically. Server-rendered language changes need navigation or an explicit client rendering implementation.

Query values need validation: allowlist languages, bound pagination and validate navigation destinations. Do not blindly redirect to arbitrary next parameters. Shareable URLs should not carry private drafts.

Runnable example

Run the JavaScript in the Console of a separate practice page. Re-run the complete example after changing its input.

function languageURL(current, language) {
  if (!['zh', 'en'].includes(language)) throw new Error('Unsupported language');
  const url = new URL(current);
  if (language === 'en') url.searchParams.set('lang', 'en');
  else url.searchParams.delete('lang');
  return url.href;
}
const current = 'https://example.com/index.php?id=42&q=CSS%20Grid#practice';
console.log(languageURL(current, 'en'));
console.log(languageURL(languageURL(current, 'en'), 'zh'));
// In an actual language-link handler, navigate to the returned URL.
// location.assign(languageURL(location.href, 'en'));

Trace and verify

The English URL preserves ID, query and fragment while adding language. Chinese removes language only. Serialization may use plus for spaces; compare decoded parameter values instead of relying on exact original punctuation.

Common mistakes and boundaries

The example domain is test input only and navigation is commented out. Fragments normally do not reach the server, so client behavior may need to preserve the current fragment.

Practice challenge

Add pagination state: a new keyword resets page to one while language switching preserves it. Write separate functions and counterexamples.

Reference solution and reasoning

Each function copies the URL and edits its owned fields. Test Unicode, ampersands and hash characters in query values to ensure they remain data rather than structure.

Further reading