URL encoding
Some characters can't appear in URLs (e.g. spaces), others have special meanings in URLs. We need to convert special characters to conform to the syntax defined in the W3 URI specification (RFC 3986). This means that URLs must contain only a subset of a special ASCII character: the letters and numbers we are familiar with, as well as some reserved characters that are used as control characters in the URL.
URL encoding processing in JavaScript
In JavaScript, both encodeURIComponent() and encodeURI() built-in functions can be URL encoded, replacing the reserved characters in the URL with their UTF-8 encoded characters.
Most browsers automatically encode URLs, such as encoding spaces to %20, but there are always some exceptions. Fortunately, browsers provide built-in URL encoding and decoding functions: encodeURI, encodeURIComponent and decodeURI, decodeURIComponent. The question is how to use these functions, and what is the difference between them.
encodeURI()
URL encoding a string is easy, just call the encodeURI and pass in the string you want to encode. This function returns the encoded URL.
decodeURI()
This function decodes and calls the decodeURI function, passing in the encoded string, and then it returns the decoded normal string.
encodeURIComponent()
The encodeURIComponent function should be used to encode the parameter values of the query string. The difference between encodeURI and encodeURIComponent is that encodeURIComponent encodes the entire string, while encodeURI ignores the protocol prefix ('http://') as well as the domain name. encodeURIComponent is designed to encode everything, while encodeURI ignores the domain name part of the URL. When youWhen you want to encode the parameter value in the URL, select the encodeURIComponent function。
decodeURIComponent()
The decodeURIComponent function will decode the encoded string of the encodeURIComponent function and restore it to its normal content.
Review:
|