One, foreword

There are a lot of articles on the difference between these three methods, but most of them are very convoluted. This article tries to explain these three methods from a practical perspective.

Escape (encoding)===>unescape(decoding)

EncodeURI ===> decodeURI

EncodeURIComponent ===>decodeURIComponent

escape(‘abc=123’) //”abc%3D123″

Escape is not in the same category

In simple terms, escape encodes strings (while the other two are urls) to make them readable on all computers.

The encoded result is %XX or %uXXXX. ASCII letters, digits, @*/+, these characters will not be encoded, the rest will. Most importantly, forget about this method when you need to encode urls. This method works for strings, not urls. In fact, I haven’t used this method in my actual work, so I won’t go into it.

3. The most common encodeURI and encodeURIComponent

Encoding urls is common, so these two methods should be of particular concern in practice. They are all encoded urls, the only difference being the range of characters to encode, where the encodeURI method does not encode ASCII letters, numbers,! @ # $& * () = : /,; ? The +’ encodeURIComponent method does not encode ASCII letters, numbers,! *()’ so encodeURIComponent encodes a larger range than encodeURI. For a practical example, encodeURIComponent encodes http:// as HTTP %3A%2F%2F whereas encodeURI does not.

Four, the most important, what occasion should I use what method

The difference is clear. Let’s talk about it from practical examples.

1. If it’s just an encoded string that has nothing to do with the URL, use escape.

2. If you need to encode the entire URL and then use the URL, use encodeURI. Such as

encodeURI("http://www.cnblogs.com/season-huang/some other thing");
Copy the code

And when you encode it, it becomes

"http://www.cnblogs.com/season-huang/some%20other%20thing";
Copy the code

Where the space is encoded as %20. But if you use encodeURIComponent, the result becomes

"http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"
Copy the code

See the difference? Even the “/” is encoded, so the whole URL is unusable.

3. When you need to encode parameters in URL, encodeURIComponent is the best method.

var param = "http://www.cnblogs.com/season-huang/"; / / param as parameters
param = encodeURIComponent(param);
var url = "http://www.cnblogs.com?next=" + param;
console.log(url) //"http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"
Copy the code

As you can see, the “/” in the argument can be encoded. If you use encodeURI, you will definitely have a problem, because the following/needs to be encoded.