JavaScript中的字符串编码函数有escape()、encodeURI()、encodeURIComponent()三种,它们的用法有着不同的特点。
escape()函数
escape()函数可以把字符串中的某些特殊字符转换成百分号(%)后跟两位十六进制数的形式,它能够对ASCII字符、汉字、Unicode字符进行编码,但是不能对特殊字符进行编码,如:@、+、/、?等,它的使用方法如下:
var str = "Hello World!"; var strEncode = escape(str); alert(strEncode); //"Hello%20World%21"
encodeURI()函数
encodeURI()函数是用来对整个URI进行编码的,它能够对字符串中的所有特殊字符进行编码,它的使用方法如下:
var str = "http://www.example.com/hello world.html"; var strEncode = encodeURI(str); alert(strEncode); //"http://www.example.com/hello%20world.html"
encodeURIComponent()函数
encodeURIComponent()函数是用来对URI的某一部分进行编码的,它能够对字符串中的所有特殊字符进行编码,它的使用方法如下:
var str = "http://www.example.com/hello world.html"; var strEncode = encodeURIComponent(str); alert(strEncode); //"http%3A%2F%2Fwww.example.com%2Fhello%20world.html"
来说,escape()函数可以对字符串中的某些特殊字符进行编码,encodeURI()函数可以对整个URI进行编码,encodeURIComponent()函数可以对URI的某一部分进行编码。