URL encoding, also known as percent-encoding, is a process of encoding special characters in a URL to make the transmitted data more secure and reliable. It helps avoid cross-site attacks while calling a remote web service.
There can be two types of characters in a URL: reserved and unreserved. The reserved characters are those characters that have special meaning within a URL. For example,
:, etc. are reserved characters, and they must not be a part of query strings or path segments. Unreserved characters have no special meaning. Using URL encoding, these characters are converted to special character sequences.
encodeURIComponent(). Both of these methods are intended to be used for different use cases. Let us start with the first.
encodeURI() method is meant to encode a complete URL. It assumes that the input is a full URL with some special characters that need encoding in it. Therefore, it doesn't encode the reserved characters (
Let us look at an example:
encodeURIComponent function should be used to encode a single URL component (like query string parameter) instead of the complete URL. It uses the
UTF-8 encoding scheme and encodes all characters with special meaning except
If you use
encodeURIComponent() to encode a full URL, everything including path separators (
/) will be encoded as shown below:
Ideally, you should use the
encodeURIComponent() method only for encoding query string parameters or path segments. Here is an example:
You should call the
encodeURIComponent() method for every single query string parameter, which might include special characters to avoid network errors and unexpected response.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5) .
Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.