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 = '';
const encodedLink = encodeURIComponent(link);
const url = `${encodedLink}`;

console.log(url); //

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.