JavaScript provides native methods to encode URI components. The main difference lies in whether structural characters (like colons, slashes, and question marks) are preserved or encoded. If you are formatting variable constants before constructing your API fetch queries, check our
Case Converter. Here is a comparison of standard JS encoding methods:
const component = "https://example.com/api?user=Jane Doe";
// encodeURI (preserves slashes, colons, and query delimiters)
console.log(encodeURI(component));
// "https://example.com/api?user=Jane%20Doe"
// encodeURIComponent (encodes all non-alphanumeric symbols)
console.log(encodeURIComponent(component));
// "https%3A%2F%2Fexample.com%2Fapi%3Fuser%3DJane%20Doe"