HTML URL Encoding
URLs can only contain a limited set of ASCII characters. URL encoding (percent-encoding) converts unsafe or reserved characters into a % followed by two hex digits, so URLs remain valid everywhere.
For example, a space becomes %20, and an ampersand within a query value becomes %26. Browsers and server frameworks usually handle this automatically, but understanding it helps debug broken links.
encodeURIComponent("text")Why encoding is needed
Characters like spaces, &, ?, and # have special meaning in URLs or aren't allowed at all, so they must be encoded to avoid breaking the link's structure.
Common encoded characters
Space becomes %20 (or +), & becomes %26, # becomes %23, and / becomes %2F when it needs to be literal rather than a path separator.
<a href="https://example.com/search?q=hello%20world">Search</a>(navigates to a search for 'hello world')%20 represents an encoded space within the URL query string.
console.log(encodeURIComponent("a&b"));a%26bencodeURIComponent() safely escapes special characters for use in a URL.
Key points
- URLs only allow a limited set of ASCII characters safely.
- Percent-encoding replaces unsafe characters with %XX hex codes.
- Space becomes %20, & becomes %26, # becomes %23.
- JavaScript's encodeURIComponent() automates this encoding.
