Phong Duong


How to encode and decode URL with Javascript

30-10-2020 | #javascript

When you request a third-party API, you may pass parameters that contain special characters. This may cause errors for your request. To avoid this situation, you need to encode the URL before sending the request.

Encode URL

Javascript has 2 functions that help you encode a URL:

  • encodeURI(): encode a full URL. It doesn't encode ~!@#$&*()=:/,;?+'
  • encodeURIComponent(): encode a part of the URL. It doesn't encode -_.!~*'()


Encode URL

const URL = "ểm tra tiếng Việt"

console.log(encodeURI(URL)) //
console.log(encodeURIComponent(URL)) //

Encode parameters

const URL = ""
const URLParam = ""
const queryParam = "Đây là tiếng Việt"

console.log(`${URL}?url=${encodeURIComponent(URLParam)}`) //
console.log(`${URL}?q=${encodeURIComponent(queryParam)}`) //

Decode URL

Javascript provides decodeURI() and decodeURIComponent()to decode a URL. You can use them to decode the corresponding encoding function's result

console.log(decodeURI("")) //ểm tra tiếng Việt
console.log(decodeURIComponent("")) //ểm tra tiếng Việt


If you want to encode a full URL, use encodeURI().

If you want to encode a part of the URL, use encodeURIComponent().

To decode, use the corresponding function.

Share: TwitterFacebookLinkedInHacker News