Monday, January 12, 2009

How to UTF-8 encode/decode using core (client side) JavaScript functionality?

So, you want to encode a string to UTF-8 or decode a UTF-8 string in JavaScript and realize that it doesn't give you built in functionality for doing it?

Don't go and implement the UTF-8 encoding and decoding yourself, as you can still use built in functionality:

var utf8 = {
encode: function(s){return unescape(encodeURIComponent(s));},
decode: function(s){return decodeURIComponent(escape(s));}
};

FireFox base64 encode/decode

If you want to encode a string using base64 in JavaScript under FireFox you can use the (somewhat undocumented method) btoa().

If you want to decode a base64 encoded string in JavaScript under FireFox you can use the (somewhat undocumented method) atob().