JS urlencode,urldecode

 1 var LittleUrl = {  
 2     // public method for url encoding  
 3     encode : function (string) {  
 4         return escape(this._utf8_encode(string));  
 5     },  
 6     // public method for url decoding  
 7     decode : function (string) {  
 8         return this._utf8_decode(unescape(string));  
 9     },  
10     // private method for UTF-8 encoding  
11     _utf8_encode : function (string) {  
12         string = string.replace(/\r\n/g,"\n");  
13         var utftext = "";  
14         for (var n = 0; n < string.length; n++) {  
15    
16             var c = string.charCodeAt(n);  
17    
18             if (c < 128) {  
19                 utftext += String.fromCharCode(c);  
20             }  
21             else if((c > 127) && (c < 2048)) {  
22                 utftext += String.fromCharCode((c >> 6) | 192);  
23                 utftext += String.fromCharCode((c & 63) | 128);  
24             }  
25             else {  
26                 utftext += String.fromCharCode((c >> 12) | 224);  
27                 utftext += String.fromCharCode(((c >> 6) & 63) | 128);  
28                 utftext += String.fromCharCode((c & 63) | 128);  
29             }  
30    
31         }  
32    
33         return utftext;  
34     },  
35    
36     // private method for UTF-8 decoding  
37     _utf8_decode : function (utftext) {  
38         var string = "";  
39         var i = 0;  
40         var c = c1 = c2 = 0;  
41    
42         while ( i < utftext.length ) {  
43    
44             c = utftext.charCodeAt(i);  
45    
46             if (c < 128) {  
47                 string += String.fromCharCode(c);  
48                 i++;  
49             }  
50             else if((c > 191) && (c < 224)) {  
51                 c2 = utftext.charCodeAt(i+1);  
52                 string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));  
53                 i += 2;  
54             }  
55             else {  
56                 c2 = utftext.charCodeAt(i+1);  
57                 c3 = utftext.charCodeAt(i+2);  
58                 string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
59                 i += 3;  
60             }  
61         }  
62         return string;  
63     }  
64 }  

 

原文地址:http://willeager.iteye.com/blog/1061824

posted on 2015-12-21 09:22  咚..咚  阅读(152)  评论(0)    收藏  举报

导航