Method 1: encodeURIComponent()
The encodeURIComponent() function is used to encode a single component of a URI, such as a query string parameter. It encodes all characters except for the following: A-Z a-z 0-9 – _ . ! ~ * ‘ ( )
Here’s an example of using encodeURIComponent():
In this example, the space character and the exclamation mark are replaced with their corresponding percent-encoded values.
Method 2: encodeURI()
The encodeURI() function is used to encode an entire URI. It encodes all characters except for the following: A-Z a-z 0-9 ; , / ? : @ & = + $ – _ . ! ~ * ‘ ( ) #
Here’s an example of using encodeURI():
In this example, only the space character is replaced with its percent-encoded value, as the other characters are considered safe for the entire URI.
It’s important to use the appropriate encoding function depending on your use case. If you’re encoding a single component like a query parameter, use encodeURIComponent(). If you need to encode an entire URI, use encodeURI().