What is encodeURI() in JavaScript?
Overview
The encodeURI() function encodes a URI by replacing characters in the given string with escape sequences. The characters that are left as they are and are not encoded are given below:
- All alphabets (including uppercase and lowercase)
- All digits from 0-9
- Other characters ; , / ? : @ & = + $ - _ . ! ~ * ’ ( ) #
An example of an escape sequence is %20, which is used to replace the space character, i.e., " ".
Parameters
encodeURI() takes a string to be encoded as input.
Syntax
encodeURI(str)
Return value
encodeURI() returns the encoded URI.
Example
console.log ( encodeURI("https://www.google.com/search?q=encodeuri example åел") )
Usage
Another similar function in JavaScript is encodeURIComponent(). Choosing which one to use can be a source of confusion if one does not understand the difference.
encodeURIis used when the string to be encoded consists of a complete URL. Therefore, “/” is not included because different parts of a URL are separated by “/”, such as the hostname, path, and query strings.encodeURIComponentis used to encode only a part of the URL, for example, the query string. Hence, the list of characters replaced by escape sequences is greater than that inencodeURI.