The decodeURI()
function is used to decode a URI by replacing escape sequences with their respective special characters. An example of an escape sequence is %20
, which is replaced by the space character when decodeURI
is applied.
decodeURI()
takes an encoded URI string as input. To get accurate results, this should be a string that was first encoded using the encodeURI
function.
decodeURI(str)
decodeURI()
returns the decoded URI.
uri_example_one = "https://www.google.com/search?q=decodeuri%20example%20%C3%A5%D0%B5%D0%BB"console.log( decodeURI(uri_example_one) )uri_example_two = "https://www.educative.io/learning%20t%C5%8D%20d%C4%97c%C5%8Dd%C4%97"console.log( decodeURI(uri_example_two) )
decodeURI
may throw an exception if the input string contains any invalid characters. Therefore, we advise using the function below inside a try-catch block:
try {var encoded_uri = "%20"var decoded_uri = decodeURI(encoded_uri)} catch(exception) {console.log(exception);}
try {var encoded_uri = "%E"var decoded_uri = decodeURI(encoded_uri)} catch(exception) {console.log(exception);}
decodeURI
is used to decode complete URIs that have been encoded using encodeURI
. Another similar function is decodeURIComponent
. The difference is that the decodeURIComponent
is used to decode a part of the URI and not the complete URI.
If given the same complete URI encoded using encodeURI
, the output would be the same for both functions because the same escape characters would be replaced in both.
However, if we want to decode a URI that was encoded using encodeURIComponent
, then the correct function to use would be decodeURIComponent
.
uri = "https://www.educative.io/learning tō dėcōdė"encoded_complete_uri = encodeURI(uri)decode_uri = decodeURI(encoded_complete_uri)decode_uri_component = decodeURIComponent(encoded_complete_uri)console.log("Complete uri being used: ", uri)console.log("decodeURI: ", decode_uri )console.log("decodeURIComponent: ", decode_uri_component)
uri = "query=?/learning tō dėcōdė"encoded_complete_uri = encodeURIComponent(uri)decode_uri = decodeURI(encoded_complete_uri)decode_uri_component = decodeURIComponent(encoded_complete_uri)console.log("Part of the uri being used: ", uri)console.log("decodeURI: ", decode_uri )console.log("decodeURIComponent: ", decode_uri_component)