How to Encode a URL in JavaScript for Use in the Query String?

Learn how to encode a URL in JavaScript to use it as a GET Param Value

To encode a URL in JavaScript to use it as a query string parameter value, you can simply use the encodeURIComponent() function. For example:

const link = 'https://designcise.com/#foo';
const encodedLink = encodeURIComponent(link);
const url = `https://example.com/?ref=${encodedLink}`;

console.log(url); // https://example.com/?ref=https%3A%2F%2Fdesigncise.com%2F%23foo

Please note that the encodeURIComponent() function escapes all characters except A-Z a-z 0-9 - _ . ! ~ * ' ( ).


Hope you found this post useful. It was published . Please show your love and support by sharing this post.