JavaScript decodeURI()

Posted by

Function

Introduction to JavaScript decodeURI() Function

The JavaScript decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously encoded using encodeURI(). It is often used to decode URLs, such as those passed as a query string parameter in the URL of a web page.

Syntax of decodeURI()

The syntax of the decodeURI() function 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”]

decodeURI(encodedURI)

[/dm_code_snippet]

Where encodedURI is the URI that has been previously encoded using the encodeURI() function.

Example of decodeURI()

Consider the following example, which uses the decodeURI() function to decode a URL 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”]

var encodedURL = "https://www.example.com/search?q=hello%20world";
var decodedURL = decodeURI(encodedURL);

console.log(decodedURL);
// Output: "https://www.example.com/search?q=hello world"

[/dm_code_snippet]

In the above example, the encoded URL string is first passed to the decodeURI() function. The decoded URL is then logged to the console.

Using decodeURI() with a Query String

The decodeURI() function can also be used to decode a query string parameter in a URL. Consider the following example:

[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 encodedURL = "https://www.example.com/search?q=hello%20world&sort=date";
var decodedURL = decodeURI(encodedURL);

console.log(decodedURL);
// Output: "https://www.example.com/search?q=hello world&sort=date"

[/dm_code_snippet]

In the above example, the encoded URL string is first passed to the decodeURI() function. The decoded URL is then logged to the console.

Conclusion

The JavaScript decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously encoded using encodeURI(). It is often used to decode URLs, such as those passed as a query string parameter in the URL of a web page.