Javascript Class that encodes urls


/ Published in: JavaScript
Save to your folder(s)

I did not, in fact write this script. I found it here:

http://www.webtoolkit.info/javascript-url-decode-encode.html


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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.