Shruti Kapoor
You might think that encodeURI and encodeURIComponent do the same thing, at least from their names. And you might be confused which one to use and when.
In this article, I will demystify the difference between encodeURI and encodeURIComponent .
URI stands for Uniform Resource Identifier. URL stands for Uniform Resource Locator.
Anything that uniquely identifies a resource is its URI, such as id, name, or ISBN number. A URL specifies a resource and how it can be accessed (the protocol). All URLs are URIs, but not all URIs are URLs.
URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded.
This means that we need to encode these characters when passing into a URL. Special characters such as & , space , ! when entered in a url need to be escaped, otherwise they may cause unpredictable situations.
encodeURI and encodeURIComponent are used to encode Uniform Resource Identifiers (URIs) by replacing certain characters by one, two, three or four escape sequences representing the UTF-8 encoding of the character.
encodeURIComponent should be used to encode a URI Component - a string that is supposed to be part of a URL.
encodeURI should be used to encode a URI or an existing URL.
encodeURI() will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
The characters A-Z a-z 0-9 - _ . ! ~ * ' ( ) are not escaped.
const url = 'https://www.twitter.com' console.log(encodeURI(url)) //https://www.twitter.com console.log(encodeURIComponent(url)) //https%3A%2F%2Fwww.twitter.com const paramComponent = '?q=search' console.log(encodeURIComponent(paramComponent)) //"%3Fq%3Dsearch" console.log(url + encodeURIComponent(paramComponent)) //https://www.twitter.com%3Fq%3Dsearch
encodeURI("http://www.mysite.com/a file with spaces.html") //http://www.mysite.com/a%20file%20with%20spaces.html
let param = encodeURIComponent('mango') let url = "http://mysite.com/?search hljs-string">"&length=99"; //http://mysite.com/?search=mango&length=99
If you have a complete URL, use encodeURI . But if you have a part of a URL, use encodeURIComponent . Interested in more tutorials and JSBytes from me? Sign up for my newsletter. or follow me on Twitter ###