EncodeURI
On web sites, URLs use special syntax—for example they encode a hash sign as a character sequence "%23." Spaces can also be encoded.
In a Node.js program, we want to encode and decode URIs when we interact with the browser's location. This does not need to be done manually (except in special cases).
EncodeURIComponent
Suppose our app creates a "component" of a URL, not an entire URL. Symbols such as the hash and ampersand should be encoded, not left in their original condition.
encodeURIComponent
, we convert valid URL characters to their encoded representation for use in a component (not a full URL).var part = "c# bird & fish"; // The encodeURIComponent method will encode hash signs. var result = encodeURIComponent(part); console.log("ENCODE BEORE: " + part); console.log("ENCODE AFTER: " + result);ENCODE BEORE: c# bird & fish ENCODE AFTER: c%23%20bird%20%26%20fish
EncodeURI
exampleThis method is like encodeURIComponent
but it does not encode certain chars like the hash symbol. These are left alone and considered part of the URL structure.
var part = "f# example"; // The encodeURIComponent method will not encode some things. // ... If you want those things encoded, use encodeURIComponent. var result = encodeURI(part); console.log("ENCODEURI: " + result);ENCODEURI: f#%20example
DecodeURI
This method does the opposite of encodeURI
—it transforms an encoded URL back into a normal string
format. We can use its decodeURIComponent
counterpart.
var part = "c%23%20example"; // Use decodeURI and decodeURIComponent methods. var result1 = decodeURI(part); var result2 = decodeURIComponent(part); console.log("DECODEURI: " + result1); console.log("DECODEURICOMPONENT: " + result2);DECODEURI: c%23 example DECODEURICOMPONENT: c# example
In my testing, replace()
calls that replace characters globally were slower than encodeURIComponent
. Three replace calls were about 3 times slower than encodeURIComponent
.
encodeURIComponent
to fix encodings—it is faster and simpler to use.It is tempting to write "replace" calls for URLs to fix their characters. This is a bad idea. With specialized methods like encodeURI
we have a faster and clearer solution.