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

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 - _ . ! ~ * ' ( ).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.