When people use JS to submit data, especially when using Chinese, they often need to URL-encode the string to be submitted. There are several ways to URL encode strings in JS, encodeURI, encodeURIComponent, and escape. In many codes I have seen, the escape function is used the most, but this function is not recommended. Let's take a look at these functions separately:
encodeURI: URL-encode the specified string, excluding : # / = & key characters in these URLs.
encodeURIComponent: Encode the characters in the string, including special characters in the URL.
escape: This is a relatively early version of JS function. There will be some problems when handling unicode characters in this function.
The code is as follows:
var url = "http: //www.abc.com?q=aa& amp;b=haha";
var encodedUrl = encodeURI(url);
alert(encodedUrl); //Output: http://www.abc.com ?q=aa&b=hehe
encodedUrl = encodeURIComponent(url);
alert(encodedUrl); //Output: http:/// /www.abc.com?q=aa&b=hehe
alert(escape( url)); //Output: http://www.abc.com?q=aa&b=%u5475%u5475
As shown above, when processing Chinese characters in the escape function, they will be converted In the form of %uxxxx, obviously this is different from the URL encoding format, and the encodeURIComponent function encoding is the most thorough. If there is no special need, the encodeURIComponent function is more commonly used. Of course, maybe we won’t have it if we use escape. What's the problem? Maybe your server-side language can parse it normally, but this function is not very standard when dealing with unicode characters, so it is recommended that you use the encodeURIComponent and decodeURIComponent functions to URL encode and decode strings. .