The encodeURIComponent() Function in JavaScript
source link: https://masteringjs.io/tutorials/fundamentals/encodeuricomponent
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The encodeURIComponent() Function in JavaScript
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.
fetch(`https://httpbin.org/get?email=${email}`);
What happens if email
has an &
, like '[email protected]¶m=somethingelse'
?
That would add an extra parameter param=somethingelse
to the query string.
encodeURIComponent()
ensures that email
.
For example:
const email = '[email protected]¶m=somethingelse';
await fetch(`https://httpbin.org/get?email?email=${email}`).
then((res) => res.json()); // { email: '[email protected]', param: 'somethingelse' }
await fetch(`https://httpbin.org/get?email=${encodeURIComponent(email)}`).
then((res) => res.json()); // { email: '[email protected]¶m=somethingelse' }
Do not encode the entire url! Just encode the individual values in the query string.
Axios
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('https://httpbin.org/get?answer=42')`
const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });
res.data.args; // { answer: 42 }
More Fundamentals Tutorials
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK