Percent-encoding, and which function to use
URLs may only contain a restricted set of characters. Everything else — spaces, accented letters, most punctuation — has to be written as a percent sign followed by the hexadecimal value of each UTF-8 byte. A space becomes %20, and é becomes %C3%A9 because it is two bytes in UTF-8.
The common mistake is escaping the wrong amount. Escaping a whole URL with the aggressive rule turns https://example.com into https%3A%2F%2Fexample.com, which is no longer a link. Escaping a single parameter value with the permissive rule leaves an & inside the value intact, which splits it into two parameters and silently corrupts the data.
The practical rule
- Building a query string from user input? Escape each value with the aggressive rule, then join them with
&and=yourself. - Have a finished URL containing spaces or non-ASCII? Use the whole-URL rule, which leaves the structure alone.
To take a URL apart and inspect its parameters, use the URL parser. For escaping text destined for HTML rather than a URL, use the HTML entity encoder.