如何使用JavaScript编码URL

How do you encode a URL in JavaScript?

您如何在JavaScript中编码URL?

Depending on what you need to do, there are 2 JavaScript functions what will help you.

根据您需要执行的操作,有2个JavaScript函数可以为您提供帮助。

The first is encodeURI(), and the second is encodeURIComponent().

第一个是encodeURI() ,第二个是encodeURIComponent()

Note: you might read about escape(), but that is deprecated and should not be used.

注意:您可能会读到有关escape() ,但已过时,不应使用。

Those 2 methods differ in which characters they do encode.

这两种方法在编码字符方面有所不同。

In details, encodeURI() does not encode ~!@#$&*()=:/,;?+ and encodeURIComponent() does not encode -_.!~*'(), encoding all the other characters. Why do they differ? Because they are meant for different uses:

详细来说, encodeURI()不对~!@#$&*()=:/,;?+进行编码,而encodeURIComponent()不对-_.!~*'()编码,而对所有其他字符进行编码。 他们为什么不同? 因为它们的用途不同:

  • encodeURI() is meant to encode a full URL

    encodeURI()用于编码完整的URL

  • encodeURIComponent() is meant to encode a single URL parameter value

    encodeURIComponent()用于编码单个URL参数值

If you were to call encodeURIComponent() on a full URL, since it does encode /, the URL path separators would be encoded as well (among other things):

如果要在完整的URL上调用encodeURIComponent() ,因为它确实对/进行了编码,那么URL路径分隔符也将被编码(除其他外):

encodeURI("http://flaviocopes.com/ hey!/")
//"http://flaviocopes.com/%20hey!/"
encodeURIComponent("http://www.example.org/a file with spaces.html")
// "http%3A%2F%2Fflaviocopes.com%2F%20hey!%2F"

MDN proposes an improvement to adhere to the RFC 3986 standard (http://tools.ietf.org/html/rfc3986), by implementing the following function:

MDN通过实现以下功能,提出了对符合RFC 3986标准( http://tools.ietf.org/html/rfc3986 )的改进:

const fixedEncodeURIComponent = (str) => {
  return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
    return '%' + c.charCodeAt(0).toString(16)
  })
}

You call it for every single parameter that you’ll add to the URL.

您为要添加到URL的每个参数调用它。

The encodeURI() and encodeURIComponent() methods have a corresponding decodeURI() and decodeURIComponent() which does the opposite job which you can use on the backend if you use Node.js.

encodeURI()encodeURIComponent()方法具有对应的decodeURI()decodeURIComponent() ,它们的功能相反,如果您使用Node.js,则可以在后端使用。

翻译自: https://flaviocopes.com/how-to-encode-url/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值