How to encode URL using JavaScript

For example, if you want to send it as part of a GET request, you may need to encode the URL.

How to encode URL in JavaScript?

Depending on the operation you need to perform, there are 2 JavaScript functions that can help you.

first of allencodeURI()And the second one isencodeURIComponent().

Note: You may readescape(), But is deprecated and should not be used.

The two methods differ in encoding characters.

In details,encodeURI()Not coded[email protected]#{{content}}amp;*()=:/,;?+withencodeURIComponent()Not coded-_.!~*'()To encode all other characters. Why are they different? Because of their different uses:

  • encodeURI()Used to encode the complete URL
  • encodeURIComponent()Designed to encode a single URL parameter value

If you want to callencodeURIComponent()On the full URL because it is actually encoded/, The URL path separator will also be encoded (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"

MDNPropose an improvement measure to comply withRFC3986 standard (http://tools.ietf.org/html/rfc3986), through the realization of the following functions:

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

You can call it for every parameter you want to add to the URL.

ThisencodeURI()withencodeURIComponent()Method has a correspondingdecodeURI()withdecodeURIComponent()If you are using the opposite job, you can use it on the backendNode.js.

Download mine for freeJavaScript beginner's manual


More js tutorials: