Objective
There are three functions in JavaScript that can encode strings, namely: Escape,encodeuri,encodeuricomponent, corresponding 3 decoding functions: Unescape,decodeuri, decodeURIComponent.
Escape () and they are not the same class
In short, escape () encodes the string (string) (and the other two URLs) to make them readable on all computers.
The effect after encoding is%XX or%uxxxx this form. Where ASCII letters, numbers, @*/+, these characters will not be encoded, the rest will.
Most crucially, when you need to encode the URL, forget this method, which is used for strings and does not apply to URLs.
Escape (' code ') //"%u7f16%u7801"unescape ('%u7f16%u7801 ') //"encode"
Most commonly used encodeURI () and encodeURIComponent ()
URL encoding is a common thing, so these two methods should be in practice to pay special attention to.
They are encoded URLs, the only difference being the coded character range, where:
The encodeURI method does not encode ASCII letters, numbers, [email protected]#$&* () =:/, for the following characters; +
The encodeURIComponent method does not encode ASCII letters, numbers, ~!* () for the following characters
So the encodeuricomponent is much larger than the encodeURI coding range.
As a practical example, encodeURIComponent will encode http:// into http%3a%2f%2f and encodeURI not. encodeURI (' https://www.baidu.com/') //"https://www.baidu.com/" encodeURIComponent (' https://www.baidu.com/') //"https%3a%2f%2fwww.baidu.com%2f"
Most importantly, what kind of occasion should I use?
The difference is very clear, and then from the actual example.
1, if just encoded string, do not have a half-penny relationship with the URL, then use escape.
2, if you need to encode the entire URL, and then need to use this URL, then use encodeURI.
3, when you need to encode the parameters in the URL, then encodeURIComponent is the best way.
varA = "http://blog.csdn.net/?ref=toolbar_logo&test= test"Escape (a)//"Http%3a//blog.csdn.net/%3fref%3dtoolbar_logo%26test%3d%u6d4b%u8bd5"Unescape ("Http%3a//blog.csdn.net/%3fref%3dtoolbar_logo%26test%3d%u6d4b%u8bd5")//"http://blog.csdn.net/?ref=toolbar_logo&test= test"encodeURI (a)//"http://blog.csdn.net/?ref=toolbar_logo&test=%E6%B5%8B%E8%AF%95"decodeURI ("http://blog.csdn.net/?ref=toolbar_logo&test=%E6%B5%8B%E8%AF%95")//"http://blog.csdn.net/?ref=toolbar_logo&test= test"encodeURIComponent (a)//"http%3a%2f%2fblog.csdn.net%2f%3fref%3dtoolbar_logo%26test%3d%e6%b5%8b%e8%af%95"decodeURIComponent ("http%3a%2f%2fblog.csdn.net%2f%3fref%3dtoolbar_logo%26test%3d%e6%b5%8b%e8%af%95")//"http://blog.csdn.net/?ref=toolbar_logo&test= test"
Escape (), encodeURI (), encodeuricomponent () Differences in detail