Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encodeURI and encodeURIComponent #37

Open
naseeihity opened this issue Dec 1, 2017 · 0 comments
Open

encodeURI and encodeURIComponent #37

naseeihity opened this issue Dec 1, 2017 · 0 comments
Assignees
Labels

Comments

@naseeihity
Copy link
Owner

naseeihity commented Dec 1, 2017

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];
  });
}
@naseeihity naseeihity added the JS label Dec 5, 2017
@naseeihity naseeihity self-assigned this Mar 23, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant