您的位置:首页 > Web前端 > JavaScript

Javascript中escape(), encodeURI()和encodeURIComponent()之精析与比较

2016-04-08 14:18 218 查看
escape(), encodeURI()和encodeURIComponent()是在Javascript中用于编码字符串的三个常用的方法,而他们之间的异同却困扰了很多的Javascript初学者,今天我就在这里对这三个方法详细地分析与比较一下。
escape() 方法
MSDN JScript Reference中如是说:
The escape method returns a string value (in Unicode format) that contains the contents of [the argument]. 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."
鄙人译:escape方法以Unicode格式返回一个包含传入参数内容的string类型的值。 Escape方法会将传入参数中所有的空格、标点符号、重音字符以及其它任何非ASCII字符替换为%xx的编码形式,其中xx与其所表示的字符的16进制数表示形式相同。如空格字符的16进制表示形式为0x20,则此时xx应为20,即escape(„ ‟) 返回“%20”。
Mozilla Developer Core Javascript Guide中如是说:
The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified hexadecimal encoding value.
鄙人译:escape和unescape方法能够帮助你编码和解码字符串。escape方法对于ISO Latin字符集中的字符组成的参数,返回其16进制编码。相对应的,unescape方法则能将16进制编码形式的参数转化成为其ASCII码形式。 encodeURI()方法
MSDN JScript Reference中如是说:
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.
鄙人译:encodeURI方法返回一个经过编码的URI。如果将encodeURI方法的编码结果传递给decodeURI方法作参数,则能得到原始的未编码的字符串。需要注意到是encodeURI方法不编码如下字符":", "/", ";", and "?"。如果想要编码这些字符,请使用encodeURIComponent方法。 Mozilla Developer Core Javascript Guide中如是说:
Encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, or three escape sequences representing the UTF-8 encoding of the character.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: