Last Updated : Jan 1, 2023
When calling a remote web service, it helps prevent cross-site attacks. In a URL, there are two types of characters: reserved and unreserved.
Within a URL, reserved characters are characters that have specific meaning. For example, reserved characters such as?, /, #,:, and others must not be used in query strings or path segments.
Characters that are not reserved have no specific meaning. These characters are converted to specific character sequences using URL encoding.
Both of these strategies are designed to be employed in a variety of scenarios. Let's start with the most basic.
- It is a method used to encode the entirety of a URL. It is assumed that the input is a complete URL containing some special characters that must be encoded.
- As a result, the reserved characters (~!$&@#*()=:/,;?+) are not encoded. Let us look at an example:
Any object, such as a string, number, boolean, null, or undefined. The uriComponent is transformed to a string before encoding.
Return value :-
The specified uriComponent encoded as a URI component is returned as a new string.
Encoding query string parameters or path segments should ideally be done via the encodeURIComponent() function. When you use encodeURIComponent() to encode an entire URL, everything will be encoded, including path separators (/).
- Instead of encoding the entire URL, use the encodeURIComponent function to encode a specific URL component (such as a query string argument), encodes all special characters with the exception of -_.!~*'() using the UTF-8 encoding scheme
- The encodeURIComponent() function encodes a URI by replacing one, two, three, or four escape sequences representing the character's UTF-8 encoding with one, two, three, or four escape sequences (For characters made up of two "surrogate" characters, there will only be four escape sequences).
- To avoid network failures and unexpected answers, you should execute the encodeURIComponent() method for each query string parameter that may contain unusual characters.
If you use Node.js, the encodeURI() and encodeURIComponent() methods have a matching decodeURI() and decodeURIComponent() function that does the opposite and may be used on the backend.