JavaScript decodeURIComponent()

Posted by

Introduction to JavaScript decodeURIComponent()

The JavaScript decodeURIComponent() method is used to decode a Uniform Resource Identifier (URI) component that was previously encoded. It is part of the JavaScript global object and can be used to convert a string of encoded characters into their actual characters. This is useful when sending data through a URL, as it allows characters like ? and & to be encoded, making it easier to read. In this tutorial, we’ll discuss how to use the decodeURIComponent() method and look at some examples.

Syntax

The syntax for the decodeURIComponent() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

decodeURIComponent(encodedURI)

[/dm_code_snippet]

Where encodedURI is a string containing an encoded URI component. This string must be encoded using the JavaScript encodeURIComponent() method.

Return Value

The decodeURIComponent() method returns a string containing the decoded version of the encoded URI component.

Examples

Let’s look at an example of how to use the decodeURIComponent() method. Assume we have the following string of encoded characters:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var encodedString = "%3Fuserid%3D12345%26password%3Dsecret";

[/dm_code_snippet]

We can use the decodeURIComponent() method to decode this string as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var decodedString = decodeURIComponent(encodedString);

[/dm_code_snippet]

This will return the following string:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

?userid=12345&password=secret

[/dm_code_snippet]

As you can see, the encoded characters (i.e. %3F and %26) have been decoded into their actual characters (i.e. ? and &).

Conclusion

In this tutorial, we discussed how to use the JavaScript decodeURIComponent() method. This method is useful for decoding a string of encoded characters into their actual characters. We looked at an example of how to use the method and discussed its syntax and return value. Now you have the knowledge you need to start using the decodeURIComponent() method in your own applications.