JavaScript Recipes: Encode and Decode URLs

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


How do you encode a URL in JavaScript?

Depending on what you need to do, there are 2 JavaScript functions that will help you.

The first is encodeURI(), and the second is encodeURIComponent().

Note: you might read about escape(), but that is deprecated and should not be used.

Differences Between the Two Methods

Those 2 methods differ in which characters they encode.

In details:

  • encodeURI() does not encode ~!@#$&*()=:/,;?+
  • encodeURIComponent() does not encode -_.!~*'()

Why do they differ? Because they are meant for different uses:

  • encodeURI() is meant to encode a full URL
  • encodeURIComponent() is meant to encode a single URL parameter value

If you were to call encodeURIComponent() on a full URL, since it does encode /, the URL path separators would be encoded as well (among other things):

encodeURI("http://flaviocopes.com/ hey!/")
//"http://flaviocopes.com/%20hey!/"

encodeURIComponent("http://www.example.org/a file with spaces.html")
// "http%3A%2F%2Fflaviocopes.com%2F%20hey!%2F"

RFC 3986 Compliance

MDN proposes an improvement to adhere to the RFC 3986 standard, by implementing the following function:

const fixedEncodeURIComponent = (str) => {
  return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
    return '%' + c.charCodeAt(0).toString(16)
  })
}

You call it for every single parameter that you’ll add to the URL.

Decoding

The encodeURI() and encodeURIComponent() methods have corresponding decodeURI() and decodeURIComponent() which do the opposite job:

decodeURI("http://flaviocopes.com/%20hey!/")
// "http://flaviocopes.com/ hey!/"

decodeURIComponent("http%3A%2F%2Fflaviocopes.com%2F%20hey!%2F")
// "http://flaviocopes.com/ hey!/"

Lessons in this unit:

0: Introduction
1: Generate Random Numbers in a Range
2: Get Index in for...of Loop
3: Unlimited Function Parameters
4: Return Result from Async Function
5: ▶︎ Encode and Decode URLs
6: Destructuring Tips
7: Number Formatting
8: Regex Recipes
9: Dynamic function name in JS