Skip to content

How to encode a URL with JavaScript

You might need to encode a URL if you are sending it as part of a GET request, for example.

How do you encode a URL in JavaScript?

Depending on what you need to do, there are 2 JavaScript functions what 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.

Those 2 methods differ in which characters they do encode.

In details, encodeURI() does not encode ~!@#$&*()=:/,;?+ and encodeURIComponent() does not encode -_.!~*'(), encoding all the other characters. Why do they differ? Because they are meant for different uses:

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"

MDN proposes an improvement to adhere to the RFC 3986 standard (http://tools.ietf.org/html/rfc3986), 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.

The encodeURI() and encodeURIComponent() methods have a corresponding decodeURI() and decodeURIComponent() which does the opposite job which you can use on the backend if you use Node.js.


→ Get my JavaScript Beginner's Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about js: