UTF-8 Encoding

Encode and decode UTF-8 strings with JS

HTML

UTF-8 Text: <input type="text" id="fromField" value="AΞⒶ😀A" defaultvalue="AΞⒶ😀A"/>&nbsp;
<button type="button" id="convertButton" class="convert-button" onclick="convert();">Convert</button><br/>
<br/>

To Hex: <input type="text" id="toHexField" value="" defaultvalue=""/><br/>
From Hex: <input type="text" id="fromHexField" value="" defaultvalue=""/><br/>
<br/>

To Binary: <input type="text" id="toBinField" value="" defaultvalue=""/><br/>
From Binary: <input type="text" id="fromBinField" value="" defaultvalue=""/><br/>
<br/>

To Base64: <input type="text" id="toB64Field" value="" defaultvalue=""/><br/>
From Base64: <input type="text" id="fromB64Field" value="" defaultvalue=""/><br/>
<br/>

To Base64url: <input type="text" id="toB64UrlField" value="" defaultvalue=""/><br/>
From Base64url: <input type="text" id="fromB64UrlField" value="" defaultvalue=""/><br/>
<br/>

JavaScript

// UTF-8 String Encode/Decode Functions

// See Also
// stackoverflow.com/questions/30106476/utf8-with-atob
// stackoverflow.com/questions/18729405/utf8-string-to-byte-array
// stackoverflow.com/questions/15481059/utf8-hex-to-binary
// stackoverflow.com/questions/14430633/text-to-binary
// stackoverflow.com/questions/9939760/integer-to-binary

// Test Strings
// UTF-8 = 'AΞⒶ😀A'
// Binary = '10000010...'
// Hex = '41ce9ee292b6f09f988041'
// URL = '%41%ce%9e%e2%92%b6%f0%9f%98%80%41'
// Base64 = 'Qc6e4pK28J+YgEE='

// More Test Strings
// UTF-8 = '€ 你好 æøåÆØÅ'
// UTF-8 = 'abc123äöüć@*_+-./'
// UTF-8 = '✓ à la mode'

// Features and Notes
// - Encode and decode UTF-8 strings to and from binary, hex, URL hex, Base64, and Base64url
// - Work around the fact that JS charCodeAt(), etc. can't give you the byte values of binary strings (just the character codes), and don't work with character codes above U+FFFF (for example, decodeURIComponent() throws an error: "URIError: malformed URI sequence")
// - Polyfills are included for the deprecated escape/unescape() functions
// - The Base64 functions work with UTF-8 strings (characters 0x80 and above), unlike atob/btoa()
// - The Base64 functions require IE 10 or higher (or polyfills for atob/btoa())

// Polyfills for deprecated escape/unescape() functions
if( !window.unescape ){
	window.unescape = function( s ){
		return s.replace( /%([0-9A-F]{2})/g, function( m, p ) {
			return String.fromCharCode( '0x' + p );
		} );
	};
}
if( !window.escape ){
	window.escape = function( s ){
		var chr, hex, i = 0, l = s.length, out = '';
		for( ; i < l; i ++ ){
			chr = s.charAt( i );
			if( chr.search( /[A-Za-z0-9\@\*\_\+\-\.\/]/ ) > -1 ){
				out += chr; continue; }
			hex = s.charCodeAt( i ).toString( 16 );
			out += '%' + ( hex.length % 2 != 0 ? '0' : '' ) + hex;
		}
		return out;
	};
}

// UTF-8 to binary
var utf8ToBin = function( s ){
	s = unescape( encodeURIComponent( s ) );
	var chr, i = 0, l = s.length, out = '';
	for( ; i < l; i...