URLs, and why encoding is not optional
A URL has parts with rules, and the same character means different things in different parts.
The parts of a URL
https://toolsdev.in/learn/http?topic=urls#encoding has a scheme, a host, a path, a query and a fragment. Each has its own rules about which characters are allowed, which is why one encoding function is not enough.
The fragment — everything after # — is never sent to the server. It is handled by the browser alone. That surprises people debugging why a value "disappeared": it was never in the request.
Percent-encoding, and picking the right function
Characters that mean something structural — ? & = # / space — have to be escaped when they appear inside a value rather than as structure. A search for "fish & chips" put into a query unescaped ends the parameter at the ampersand and invents a new one.
JavaScript gives you two functions and they are not interchangeable. encodeURIComponent escapes those structural characters and is what you want for a single value. encodeURI leaves them alone because it is for a whole URL. Using encodeURI on a value is the bug that lets a stray & split it in two.
A space becomes %20 in a path and may be + in a query string, because form encoding and URL encoding are different conventions that meet in the same place. Decode with the matching rule or you will turn a genuine plus sign into a space — which is how phone numbers lose their country code.
Worked examples
A value containing structure
/fish & chips?/Against:
Encoded as a component: fish%20%26%20chips%3FUnescaped, the & ends the parameter and the ? is meaningless mid-query — the value silently becomes two.
Check yourself
Practice questions written for this lesson — not past exam papers.
Practise every question in this subject
Which part of a URL never reaches the server?
You are putting one search term into a query string. Which function?