HTML URL Resolution and Encoding
Resolve a URL against its base
A URL attribute contains source text, whereas a reflected property such as anchor.href exposes the resolved URL. The first base element with href supplies the document base; the base URL can affect fragment links too. A URL has structured components, not just a concatenated string.
<output id="result"></output><script> const parsed = new DOMParser().parseFromString("<base href=\"https://example.com/guide/\"><a href=\"../notes?q=html#top\">Read</a>", "text/html"); const a = parsed.querySelector("a"); const result = a.getAttribute("href") + " | " + a.href; document.querySelector("#result").textContent = String(result);</script>Expected output: ../notes?q=html#top | https://example.com/notes?q=html#top
Separate HTML escaping from URL encoding
HTML character references escape markup syntax; URL percent-encoding represents bytes in URL components. For query parameters use URLSearchParams rather than manually joining strings. Its form-style serialization encodes spaces as + and literal plus signs as %2B. The URL API does not make untrusted destinations safe; validate schemes and origins separately.
<output id="result"></output><script> const params = new URLSearchParams(); params.set("q", "A+B & C"); const result = params.toString(); document.querySelector("#result").textContent = String(result);</script>Expected output: q=A%2BB+%26+C
UTF-8 bytes and non-ASCII values
HTML decoding turns response bytes into characters; use UTF-8 consistently in the document and HTTP metadata. URL encoding is a later operation. This example uses the UTF-8 based encodeURIComponent function for a single component, not an entire URL. A JavaScript string experiment cannot test raw HTTP byte decoding.
<output id="result"></output><script> const encoded = encodeURIComponent("é"); const result = encoded + " / " + decodeURIComponent(encoded); document.querySelector("#result").textContent = String(result);</script>Expected output: %C3%A9 / é
Common mistakes and practice
Use & in HTML markup for an unambiguous literal ampersand between query parameters, and use URLSearchParams for values. Avoid double encoding already encoded data; treat raw input, URL serialization and HTML attribute serialization as distinct operations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML URL Resolution and Encoding — Knowledge Check
Apply the internals concepts taught in this lesson.
Which anchor API returns the source attribute?
What does a document base affect?
How does URLSearchParams serialize a space?
How is a literal plus serialized by URLSearchParams?
Should encodeURIComponent be applied to an entire absolute URL?