Skip to Content
Course content

246: encodeURIComponent and decodeURIComponent

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've all been there: you're building a feature where you need to pass some user-generated data through a URL, like a search query or a username. When I first started out, my go-to move was simple string concatenation or a template literal. It seems intuitive. If you want to send a search term to your backend, you just tack it onto the end of the string.

const query = "JavaScript & TypeScript";
const url = `https://api.example.com/search?q=${query}`;
// Result: https://api.example.com/search?q=JavaScript & TypeScript

The moment the URL breaks

That looks fine in a console log, but it's a ticking time bomb. The problem is that URLs have a very strict set of reserved characters. Characters like &, ?, #, and = aren't just text; they are functional markers that tell the browser and the server how the URL is structured.

In the example above, the & in "JavaScript & TypeScript" is the killer. The server won't see a single query parameter called q with the value "JavaScript & TypeScript". Instead, it'll see a parameter q equal to "JavaScript " and then a second, mysterious parameter called TypeScript with no value. Your search logic will fail, and you'll spend an hour wondering why your backend is only receiving half the string.

Using encodeURIComponent for safety

This is where encodeURIComponent() comes in. I think of it as a "sanitizer" for any piece of data that's going to live inside a URL component. It takes those dangerous reserved characters and converts them into a UTF-8 encoded sequence that the browser can safely transmit without misinterpreting the URL structure.

const query = "JavaScript & TypeScript";
const safeQuery = encodeURIComponent(query); 
const url = `https://api.example.com/search?q=${safeQuery}`;
// Result: https://api.example.com/search?q=JavaScript%20%26%20TypeScript

Now, the & becomes %26 and the spaces become %20. The server receives this, recognizes the encoding, and reconstructs the original string perfectly. I'll give you a pro-tip here: don't confuse this with encodeURI(). I've seen a lot of devs use that by mistake. encodeURI() is meant for encoding a full, complete URL—it purposely ignores characters like & and ? because it assumes they are supposed to be there as part of the URL's structure. Since we are encoding a component (the value of a parameter), encodeURIComponent() is the only correct choice.

Getting the data back with decodeURIComponent

On the flip side, if you're manually parsing a URL or receiving an encoded string from a legacy API, you'll need to reverse the process. While modern browser APIs like URLSearchParams often handle the decoding for you automatically, there are plenty of times when you'll find yourself holding a string like "Hello%20World%21" and needing it back in human-readable form.

That's where decodeURIComponent() lives. It's the mirror image of the encoder; it looks for those % sequences and turns them back into their original characters.

const encodedValue = "JavaScript%20%26%20TypeScript";
const decodedValue = decodeURIComponent(encodedValue);
console.log(decodedValue); // "JavaScript & TypeScript"

Just be careful: if you try to decode a string that isn't actually a valid URI-encoded sequence, JavaScript will throw a URIError. If you're dealing with unpredictable data from a third party, it's a good habit to wrap your decoding in a try-catch block so one malformed string doesn't crash your entire application.




📋 Practical Task

Build a Robust User Profile Link Generator

You are building a tool that generates "Share" links for user profiles. The profile links must include the user's display name and their favorite hobby as query parameters. Because users can pick any name or hobby (e.g., "R&B Lover" or "Coding #101"), you must ensure the URL is valid.

Requirements:

  • Create a function called generateProfileLink(name, hobby).
  • The base URL is https://social.app/profile.
  • The function should return a URL string where the name and hobby are properly encoded as query parameters.
  • Test your function with the following inputs: name: "Jane & Joe", hobby: "Reading & Writing".
  • Verify that the final string contains %26 instead of & for the values.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.