naseeihity / LearnToLearn

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

encodeURI and encodeURIComponent

naseeihity opened this issue · comments

encodeURI和encodeURIComponent的区别在于前者被设计来用于对完整URL进行URL Encode,于是URL中的功能字符,比如&, ?, /, =等等这些并不会被转义;而后者被设计来对一个URL中的值进行转义,会把这些功能字符也进行转义。应用场景最常见的一个是手工拼URL的时候,对每对KV用encodeURIComponent进行转义。

作者:Jim Liu
链接:https://www.zhihu.com/question/21861899/answer/43469947
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

具体使用中,如果对整个URL进行编码就使用encodeURI,但更多场景中我们只需要对相关参数进行编码,即https:// + location + /&key=encodeURIComponent(value)

具体的编码:

Char  encUrI  encURIComp  escape
*     *       *           *
.     .       .           .
_     _       _           _
-     -       -           -
~     ~       ~           %7E
'     '       '           %27
!     !       !           %21
(     (       (           %28
)     )       )           %29
/     /       %2F         /
+     +       %2B         +
@     @       %40         @
?     ?       %3F         %3F
=     =       %3D         %3D
:     :       %3A         %3A
#     #       %23         %23
;     ;       %3B         %3B
,     ,       %2C         %2C
$     $       %24         %24
&     &       %26         %26
      %20     %20         %20
%     %25     %25         %25
^     %5E     %5E         %5E
[     %5B     %5B         %5B
]     %5D     %5D         %5D
{     %7B     %7B         %7B
}     %7D     %7D         %7D
<     %3C     %3C         %3C
>     %3E     %3E         %3E
"     %22     %22         %22
\     %5C     %5C         %5C
|     %7C     %7C         %7C
`     %60     %60         %60

more

xss防御中转义

var entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}