1. Differences:
- encodeURI()
encodeURI() is usually used to transcode the entire URL. URL metacharacters and semantic characters will not be transcoded. URL metacharacters:
URL metacharacters: semicolon (;), comma (,), slash (/), question mark (?), colon (:), at (@), &, equal sign (=), plus sign (+) , dollar sign ($), pound sign (#)
Semantic characters: a-z, A-Z, 0-9, hyphen (-), underline (_), dot (.), exclamation mark (!), tilde (~), asterisk (*), single quote (' ;), parentheses (())
- encodeURIComponent()
encodeURIComponent() is usually only used to transcode URL components, such as the string after ? in the URL; all characters except semantic characters will be transcoded, that is, metacharacters will also be transcoded.
Note:If the entire link is transcoded by encodeURIComponent(), the link cannot be accessed by the browser and needs to be decoded before it can be accessed normally.
2. Usage scenarios:
Under normal circumstances we use encodeURI, such as:
console.log(encodeURI("http://example.com/pagephp?id=123&age=23&sex=\\gril"));
// http://example.com/pagephp?id=123&age=23&sex=%5Cgril
When to use encodeURIComponent:
Use encodeURIComponent when there is a callback address in the parameter
https://www.baidu.com/s?returnURL=http://www.test.com/
The link contains a callback address, and the callback address is another URL. At this time, we need to use encodeURIComponent() to transcode the callback address. In this way, multiple http://, multiple & will not appear in the URL. ; Such special characters; facilitate processing of callback addresses; the above links are processed as follows:
// 对URL中的回调链接进行转码
'https://www.baidu.com/s?returnURL=' +encodeURIComponent('http://www.test.com/')
//输出: "https://www.baidu.com/s?returnURL=http%3A%2F%2Fwww.test.com%2F"