At the past, you may have heard about escape() function encodes a string to make a string portable, so it can be transmitted across any network to any computer that supports ASCII characters. However, it was deprecated in JavaScript version 1.5. Now, we should use encodeURI() or encodeURIComponent() instead.
The main difference of these two functions is the encoding range.
encodeURI
will not encode ASCII alphabet, number and ~!@#$&*()=:/,;?+.-_'
encodeURIComponent
will not encode ASCII alphabet, number and ~!*().-_'
Range of encoding: encodeURIComponent > encodeURI
For example:
encodeURI("https://abc-def.com/index.php?name=David Beckham")
//"https://abc-def.com/index.php?name=David%20Beckham"encodeURIComponent("https://abc-def.com/index.php?name=David Beckham")
//"https%3A%2F%2Fabc-def.com%2Findex.php%3Fname%3DDavid%20Beckham"
We can see that the result of encodeURI
is still a valid URI, but the result of encodeURIComponent
is not, because it will encode the symbol :/
.
When to use encodeURI
?
encodeURI
is to process the entire URI. It accepts the protocol, host, port and only encode the path and query.
When to use encodeURIComponent
?
encodeURIComponent
is to process part of the URI, e.g. query strings.
For encodeURI
you can retrieve the original data by using decodeURI
and for encodeURIComponent
you can use decodeURIComponent
.
For example:
decodeURI("https://abc-def.com/index.php?name=David%20Beckham")
//"https://abc-def.com/index.php?name=David Beckham"decodeURIComponent("https%3A%2F%2Fabc-def.com%2Findex.php%3Fname%3DDavid%20Beckham")
//"https://abc-def.com/index.php?name=David Beckham"