http://www.sislands.com/coin70/week6/encoder.htm

URL Encoding & Decoding

Suppose you have a message and it says:

Some+website+you+got%21
%0D%0AGood+luck%28you%27ll+need+it%29
%0D%0A7E%7E+The+Slug+%7E%7E

What The Slug is trying to say is:

Some website you got!
Good luck (you'll need it)
~~ The Slug ~~

The string above is called URL Encoding, a scheme in which text data transmitted to web servers is encoded by replacing spaces (" ") with plus signs ("+") and non alpha numeric characters are replaced by their ASCII equivalents.

So, how do I convert this stuff? You could do a search and replace with an ASCII chart and tediously replace the plus signs ("+") with spaces (" ") and the ASCII representations (like %21) with their non alphanumeric counterparts (like "!"). Or you could change the ENCTYPE property of your <FORM> Object. The default encoding type is "text/urlencoded", which sends URL Encoded text to the server. Change ENCTYPE to "text/plain" and that's exactly what you get - plain text that doesn't have to be decoded. Still, it's good to know how to decode URL Encoded text and one of the simplest ways is to use JavaScript to write a simple Encoder/Decoder.

It's almost trivially simple to URL Encode text because JavaScript has two functions:

  1. escape() and

  2. unescape()

which translate text into ASCII and ASCII into text. For example, with unescape() you can convert the ASCII representations to their non alphanumeric equivalents, all that's left is to replace the plus signs ("+") with spaces (" "). Here are two simple URL Decoding scripts:

Using String charAt() Using RegExp - Search & Replace

function decode(str) {
     var result = "";

     for (var i = 0; i < str.length; i++) {
          if (str.charAt(i) == "+") result += " ";
          else result += str.charAt(i);

          return unescape(result);
     }
}

function decode(str) {
     return
unescape(str.replace(/\+/g, " "));
}

Type a message into the text box below and click Encode. The script URL Encodes your message just like your web server would and the results appear in the lower text box. Now just click Decode and a script similar to the one above Decode your message back into it's original form.