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 = 'https://google.com';
const encodedURL = "https://coderslang.com?ref=" + encodeURIComponent(urlParam);

console.log(encodedURL);

Here’s the result.

https://coderslang.com?ref=https%3A%2F%2Fgoogle.com

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 = 'https://google.com';
const baseURL = 'https://coderslang.com';

console.log(`${baseURL}?ref=${encodeURIComponent(urlParam)}`);
console.log(`${baseURL}?ref=${encodeURI(urlParam)}`);
console.log(`${baseURL}?ref=${escape(urlParam)}`);

The output is different this time:

https://coderslang.com?ref=https%3A%2F%2Fgoogle.com
https://coderslang.com?ref=https://google.com
https://coderslang.com?ref=https%3A//google.com

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