DEV Community

Ion Prodan
Ion Prodan

Posted on • Originally published at yon.fun on

Difference between encodeURI and encodeURIComponent

Difference between encodeURI and encodeURIComponent

I was pretty sure I'm using encodeURI and encodeURIComponent rightly till I faced a big problem! LOL πŸ˜‚. When I solved my issue, I finally understood what's the difference between them. So let's find out!

What are they

As you may know, in javascript encodeURI and encodeURIComponent are used to encode Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. (MDN)

The difference

There aren't big differences, the unique difference is that encodeURI() function encodes special characters, except: , / ? : @ & = + $ # whereas encodeURIComponent() function encodes special characters and in additional the characters which encodeURI doesn't encode!

When and what to use

If you're encoding a string to put in a URL component (a query string parameter), you should use encodeURIComponent, and if you're encoding an existing URL, use encodeURI. It's simple! 😎

Some references:

MDN encodeURIComponent.

MDN encodeURI.

Have you had any bad experiences with them by now?

Top comments (5)

Collapse
 
androidyue1314 profile image
androidyue

Cool. Very concise.

Collapse
 
wanoo21 profile image
Ion Prodan

Thanks!

Collapse
 
alexalannunes profile image
Alex Alan Nunes

Thankss :)

Collapse
 
heyfirst profile image
First Kanisorn Sutham

Thanks!

Collapse
 
wanoo21 profile image
Ion Prodan

You're welcome!