A query string and an HTML page do not escape text the same way.
This string is fine in a sentence:
<Hello World> & "KeptTools"?q=1
Put it in a URL without encoding, and & starts a new parameter. Put it in HTML without escaping, and < starts a tag. Those are two different jobs.
I use a small encoder for both. It runs in the browser, so the string is not uploaded.
https://kepttools.com/url-html-encoder
URL encoding
URL encoding turns characters that have a special meaning in a URL into % sequences.
The tool uses encodeURIComponent, which is the right function for a query value or a path segment. The sample becomes:
%3CHello%20World%3E%20%26%20%22KeptTools%22%3Fq%3D1
< is %3C, a space is %20, & is %26, " is %22, and ? is %3F.
encodeURI is the other common function, and it is not the same. It leaves &, ?, and = alone, because those characters structure a full URL. Use that when you already have a complete address. Use encodeURIComponent when the text is one value you are about to drop into a query string.
Do not run encodeURIComponent on a whole URL. It will also encode https:// and the ?, and the link will break.
HTML escaping
HTML escaping is for text that should be shown, not parsed.
The same sample, on HTML Encode, becomes:
<Hello World> & "KeptTools"?q=1
< becomes <, > becomes >, & becomes &, and " becomes ". A browser then displays the characters instead of treating them as markup. An apostrophe is escaped as '.
This is the step you want before you insert user text into HTML. URL encoding does not do it. %3C is not the same thing as <.
Decoding
Each mode has a reverse.
URL Decode turns the % sequences back into characters. A broken sequence, such as a % that is not followed by two hex digits, does not decode. The page reports that the encoding is invalid.
HTML Decode turns the entities back into <, >, &, and quotes.
What stays on the machine
Paste the text, or load the sample, pick URL Encode, URL Decode, HTML Encode, or HTML Decode, and copy the result. Nothing is sent to a server.
If you are building a link, encode the value. If you are showing the value on a page, escape it for HTML. Do one, then the other, when you need both.
Top comments (0)