DEV Community

Phong Duong
Phong Duong

Posted on • Originally published at on

How to encode and decode URL with 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)) //
Enter fullscreen mode Exit fullscreen mode

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)}`) //
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode


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.

Top comments (0)