HTML URL Encode
A URL has components such as a scheme, host, path, query, and fragment. Encoding a value correctly prevents its characters from being mistaken for separators in those components.
How it works
- Use URL and URLSearchParams in JavaScript when building URLs from values. They handle many encoding details more reliably than string concatenation.
- A query value can contain characters such as & and spaces that need encoding. Do not percent-encode a complete URL as though it were one query value.
- When a URL appears inside an HTML attribute, HTML escaping is a separate layer. A query separator is written & in the HTML source.
A practical example
<a href="search.html?q=tools%20%26%20repairs">Search tools and repairs</a>
<script>
const url = new URL('search.html', location.href);
url.searchParams.set('q', 'tools & repairs');
console.log(url.href);
</script>
The ampersand inside the search term stays part of that value instead of becoming an extra parameter separator. The JavaScript variant is useful when the term is supplied at runtime.