How to Encode an Email in JavaScript for Use in the Query String?

To use an email in the query string component of a URL, you can encode it using the encodeURIComponent() function in JavaScript. This would encode all characters except A-Z a-z 0-9 - _ . ! ~ * ' ( ). For example:

const email = '[email protected]';
const encodedEmail = encodeURIComponent(email);
const url = `https://example.com/?email=${encodedEmail}`;

console.log(url); // https://example.com/?email=foo.bar_baz%2B10%40bar.com

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.