日期:2014-05-16  浏览次数:20368 次

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”。

        注:unescape()方法:解码用 escape 方法进行了编码的 String 对象。
                                unescape(charstring)
                                必选项 charstring 参数是要解码的 String 对象。
                                unescape 方法返回一个包含 charstring 内容的字符
                                串值。所有以%xx十六进制形式编码的字符都用ASCII字
                                符集中等价的字符代替。以%uxxxx格式(Unicode字符)
                                编码的字符用十六进制编码xxxx的Unicode字符代替。

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方法。
 
encodeURIComponent()方法:
        MSDN JScript Reference中如是说:
        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.
        翻译如下:
        encodeURIComponent()方法返回一个编码过的URI。如果将encodeURIComponent()方法的编码结果传递给encodeURIComponent()方法作参数,则能得到原始的未编码的字符串。因为encodeURIComponent()方法会编码所有的字符,所以如果待编码的字符串是用来表示一个路径(如/dir1/dir2/index.htm)时,就一定要小心使用了。‘/’符号会被其编码之后,将不再是一个有效的路径标识符,所以不能被web服务器正确地识别。当字符串包含一个单独的URI component(指?后面的请求参数)的时候,请使用此方法。