JavaScript encodeURI()

Posted by

Introduction to JavaScript encodeURI()

The JavaScript encodeURI() function is a built-in function that allows you to encode a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. It is used to create web addresses and other URIs.

Syntax of JavaScript encodeURI()

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

encodeURI(uri)

[/dm_code_snippet]

Where uri is a string containing the Uniform Resource Identifier to be encoded.

Examples of JavaScript encodeURI()

Let’s look at some examples of using the JavaScript encodeURI() function.

The following example encodes a URL:

[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”]

let url = "https://www.example.com/my page";
let encodedUrl = encodeURI(url);

// encodedUrl = "https://www.example.com/my%20page"

[/dm_code_snippet]

The following example encodes a query 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”]

let query = "name=John&age=30";
let encodedQuery = encodeURI(query);

// encodedQuery = "name=John&age=30"

[/dm_code_snippet]

Conclusion

In this tutorial, we’ve discussed the JavaScript encodeURI() function, its syntax, and some examples of how to use it. We hope you’ve found this tutorial helpful.