Home > Article > Web Front-end > How to encode and convert url in javascript
Javascript method of encoding and converting URLs: 1. Use the encodeURI() function to encode the string as a URI; 2. Use the encodeURIComponent() function to encode the string as a URI component.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In the project, the url encountered a problem of failure to parse parameters and array objects. It was solved by transcoding, but the actual principle was not clear. I studied JS transcoding and decoding.
There are three functions in Javascript language used for encoding.
escape()
encodeURIComponent()
The difference between three encoding methods:
escape and unescape:
escape: cannot Used directly for URL encoding, its real function is to return the Unicode encoding value of a character, so the specified string can be encoded.
Except for ASCII letters, numbers, and punctuation marks "@ * _ - . /", all spaces, punctuation marks, special characters, and other non-ASCII characters will be converted into characters in the format of %xx (hexadecimal numbers) coding. That is, escape does not encode characters. There are 69 characters : *, , -, ., /, @, _, 0-9, a-z, A-Z.
The corresponding decoding function is unescape();
##encodeURI and decodeURI: **encodeURI()** is the function actually used to encode URLs in Javascript. The entire URL is encoded. In addition to common symbols, symbols with special meanings in the URL "; / ? : @ & = $ , #" are not encoded. After encoding, output the UTF-8 form of the symbol and add % before each byte. Note that encodeURI() does not encode single quotes. The corresponding decoding function of
decodeURI().
encodeURIComponent and decodeURIComponent
encodeURIComponent are used to individually encode the components of the URL. , rather than encoding the entire URL. Therefore, the symbols "; / ? : @ & = $ , #" that are not encoded in encodeURI() will all be encoded in encodeURIComponent().
Because encodeURIComponent() will encode more characters, such as "/" and other characters. If the string contains several parts of the URI, this cannot be used for encoding. Otherwise, the URL will display incorrectly after the "/" character is encoded. Therefore, when passing parameters, parameters containing special characters may cause interruptions.javascript advanced tutorial]
The above is the detailed content of How to encode and convert url in javascript. For more information, please follow other related articles on the PHP Chinese website!