URL Encoding & Decoding

Suppose you have a message and it says:


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) {
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.