You can use built-in JavaScript functions encodeURIComponent(str), encodeURI(str) or escape(str) to encode your URLs.

Here’s how you can use it.

const urlParam = '';
const encodedURL = "" + encodeURIComponent(urlParam);


Here’s the result.

There are some differences between these functions.

  • encodeURIComponent(str) doesn’t encode the symbols ~!*()'
  • encodeURI(str) doesn’t encode the characters~!@#$&*()=:/,;?+'
  • escape(str) doesn’t encode @*/+

Let’s try to use all three functions to see what’s different about the output.

I’ll also extract the base URL into a separate constant to make it reusable.

const urlParam = '';
const baseURL = '';


The output is different this time:

So, if you want to encode only part of the URL, it’s best to use the function encodeURIComponent().