只是尝试encodeURI()和encodeURIComponent()你自己...
console.log(encodeURIComponent('@#$%^&*'));
输入:@#$%^&*。输出:%40%23%24%25%5E%26*。所以,等等,发生了什么事*?为什么没有转换?TLDR:您实际上想要fixedEncodeURIComponent()和fixedEncodeURI()。很长的故事...
你不应该使用encodeURIComponent()or encodeURI()。根据 MDN 文档,您应该使用fixedEncodeURIComponent()and 。fixedEncodeURI()
关于encodeURI()...
如果希望遵循更新的 RFC3986 的 URL,它保留方括号(用于 IPv6),因此在形成可能是 URL 一部分的内容(例如主机)时不编码,以下代码片段可能会有所帮助:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
关于encodeURIComponent()...
为了更加严格地遵守 RFC 3986(保留 !、'、(、) 和 *),即使这些字符没有正式的 URI 分隔用途,也可以安全地使用以下内容:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
那么区别是什么呢? fixedEncodeURI()并fixedEncodeURIComponent()转换同一组值,但fixedEncodeURIComponent()也转换此组:+@?=:*#;,$&. 该集合用于GET参数(&、+等)、锚标记(#)、通配符标记(*)、电子邮件/用户名部分(@)等。
例如 -如果您使用encodeURI(),user@example.com/?email=me@home将不会正确地将第二个发送@到服务器,除非您的浏览器处理兼容性(Chrome 自然经常这样做)。