The encodeURIComponent() Function in JavaScript

Aug 15, 2022

The encodeURIComponent() function in JavaScript allows you to encode special characters in your query string that would otherwise change the meaning of your query string.

Characters like +, /, and & are special. For example, suppose you wanted to send an HTTP request with the user's email address in the query string.


What happens if email has an &, like ''? That would add an extra parameter param=somethingelse to the query string.

encodeURIComponent() ensures that email. For example:

const email = '';

await fetch(`${email}`).
  then((res) => res.json()); // { email: '', param: 'somethingelse' }

await fetch(`${encodeURIComponent(email)}`).
  then((res) => res.json()); // { email: '' }

Do not encode the entire url! Just encode the individual values in the query string.


If you're using Axios query params, you don't need to use encodeURIComponent(). Axios calls encodeURIComponent() for you.

const axios = require('axios');

// Equivalent to `axios.get('')`
const res = await axios.get('', { params: { answer: 42 } });; // { answer: 42 }

More Fundamentals Tutorials