escape() & encodeURI() & encodeURIComponent()


escape() & encodeURI() & encodeURIComponent()这三个函数都可以用来对URI进行encode或过滤特殊字符(#/$&+=?/等)。我的经验是最好用encodeURIComponent()(需要IE 5.5以上,FireFox当然没问题),因为对UTF-8支持比较好,不会遇到中文乱码问题,否则还需要进行编码转换,很麻烦的。Terac Rome就是用的encodeURIComponent(),del.icio.us和365key用的是escape()。当然,有人这三个函数都不用,自己写过滤函数,我觉得那纯粹是浪费精力。

下面是MSDN上对这三个函数的解释:

escape(charString)

The escape method returns a string value (in Unicode format) that contains the contents of charstring. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space is returned as "%20."

Characters with a value greater than 255 are stored using the %uxxxx format.

Note The escape method should not be used to encode Uniform Resource Identifiers (URI). Use encodeURI and encodeURIComponent methods instead.

http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthescape.asp

encodeURI(URIString)

The encodeURI method returns an encoded URI. If you pass the result to decodeURI, the original string is returned. The encodeURI method does not encode the following characters: ":", "/", ";", and "?". Use encodeURIComponent to encode these characters.

http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthfencodeuri.asp

encodeURIComponent(encodedURIString)

The encodeURIComponent method returns an encoded URI. If you pass the result to decodeURIComponent, the original string is returned. Because the encodeURIComponent method encodes all characters, be careful if the string represents a path such as /folder1/folder2/default.html. The slash characters will be encoded and will not be valid if sent as a request to a web server. Use the encodeURI method if the string contains more than a single URI component.

http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthencodeuricomponent.asp
encodeURIComponent 方法返回一个已编码的 URI。如果将编码结果传递给 decodeURIComponent,则将返回初始的字符串。因为 encodeURIComponent 方法将对所有字符编码,请注意,如果该字符串代表一个路径,例如 /kyle/blogpost.asp,则其中的斜杠也将被编码,这样,当该字符串作为请求发送到 Web 服务器时它将是无效的。如果字符串中包含多个 URI 组件,请使用 encodeURI 方法进行编码。
【例子】encodeURIComponent('/?&神泥') 返回 %2F%3F%26%E7%A5%9E%E6%B3%A5

encodeURI 方法返回一个已编码的 URI。如果将编码结果传递给 decodeURI,则将返回初始的字符串。encodeURI 不对下列字符进行编码:“:”、“/”、“;”和“?”。请使用 encodeURIComponent 对这些字符进行编码。
【例子】encodeURI('/?&神泥') 返回 /?&%E7%A5%9E%E6%B3%A5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值