How to encode a query string so that it is the value of another query string in JavaScript?

Sometimes, we want to encode a query string so that it is the value of another query string in JavaScript.

In this article, we’ll look at how to encode a query string so that it is the value of another query string in JavaScript.

How to encode a query string so that it is the value of another query string in JavaScript?

To encode a query string so that it is the value of another query string in JavaScript, we use the encodeURIComponent function.

For instance, we write

const c = "d e";
const query = "?a=b&c=" + encodeURIComponent(c);
const uri = "http://www.example.com/script?query=" + encodeURIComponent(query);

to call encodeURIComponent with c to return a URL encoded version of string c.

Then we append that to the "http://www.example.com/script?query=".

Conclusion

To encode a query string so that it is the value of another query string in JavaScript, we use the encodeURIComponent function.