Escapes, Base64, URL Encoding
Level 4 · Characters and escapes
How to write a character that would otherwise mean something else. Backslash escapes in code, Base64 for bytes, and percent signs in web links.
Course contentsLesson 9 of 11
Level 1 · Files and formats
Level 2 · Data formats
Level 3 · Config and docs files
Level 4 · Characters and escapes
Level 5 · IDs, dates and patterns
After this lesson you can
- Put a quote inside quoted text
- Explain why Base64 is not a secret
- Read %20 in a web link
12 mincovers 3 glossary entries
Worth reading first: ASCII, Unicode and UTF-8
How to write a character that means something else
Some characters already have a job, so you need a trick to write them as plain text. An escape character, most often the backslash, says the next character is special. Base64 writes any bytes with just 64 safe characters. URL encoding turns unsafe characters in a web link into codes, so a space becomes %20.
In code, a quote ends a piece of text. To put a quote inside one, you write a backslash before it: \". Some pairs stand for hidden characters, like \n for a new line and \t for a tab. To write a real backslash, you type two.
Forgetting the backslash is a classic bug. The text ends early, at the inner quote, and the rest of the line becomes broken code. Your editor's colours often show it: the text colour stops in the wrong place.
Base64 lets binary data travel where only text can go, like inside an email or a JSON file. It uses A to Z, a to z, 0 to 9, plus and slash. Every 3 bytes become 4 characters, so the result is about a third bigger.
Base64 is not a secret code. Anyone can turn it back in one step, with no key. It only changes how the bytes look. Never use it to hide a password.
A web link can only hold some characters safely. URL encoding swaps the rest for a percent sign and two hex digits: a space becomes %20, and & becomes %26. Letters, digits and the four marks - . _ ~ stay as they are.
Browsers do this for you as you type. Code that builds a link has to do it on purpose. The common slip is doing it twice, which turns %20 into %2520 and leaves a stray %20 on the page.
console.log("She said \"hi\"\nBye")
// She said "hi"
// Bye
encodeURIComponent("fish & chips")
// 'fish%20%26%20chips'$ echo -n "Hi Emma" | base64
SGkgRW1tYQ==
$ echo -n "SGkgRW1tYQ==" | base64 -d
Hi EmmaWorked example
Jack's search link breaks
Jack's shop builds a search link from what people type. A search for fish & chips finds only fish, and 0 results for chips.
The & split the link in two. He runs the words through encodeURIComponent, the & becomes %26, and the search finds all 14 dishes.
The words for this lesson3
Check yourself
Is a password safe if I store it as Base64?
Finished this lesson?
Marking it complete also marks its 3 glossary entries learned, which updates your roadmap and your saved page. 0 are already marked.