How can you encode a string to Base64 in JavaScript?
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
javascript base64
add a comment |
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
javascript base64
2
Here is best way to base64_encode and base64_decode using javascript. See below links. phpjs.org/functions/base64_encode:358 phpjs.org/functions/base64_decode:357
– gautamlakum
Mar 28 '11 at 13:39
here is another jquery plugin fo base64 encode/decode
– zahid9i
Mar 14 '12 at 18:04
Check microjs: microjs.com/#base64
– Vinod Srivastav
Mar 1 '16 at 14:16
Referenced in meta question Basically identical answers - Only difference: correction of errors.
– Peter Mortensen
Jul 16 '18 at 6:09
add a comment |
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
javascript base64
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
javascript base64
javascript base64
edited Nov 13 '18 at 20:50
DarkAjax
12.7k104159
12.7k104159
asked Oct 29 '08 at 13:34
usernameusername
6,181113542
6,181113542
2
Here is best way to base64_encode and base64_decode using javascript. See below links. phpjs.org/functions/base64_encode:358 phpjs.org/functions/base64_decode:357
– gautamlakum
Mar 28 '11 at 13:39
here is another jquery plugin fo base64 encode/decode
– zahid9i
Mar 14 '12 at 18:04
Check microjs: microjs.com/#base64
– Vinod Srivastav
Mar 1 '16 at 14:16
Referenced in meta question Basically identical answers - Only difference: correction of errors.
– Peter Mortensen
Jul 16 '18 at 6:09
add a comment |
2
Here is best way to base64_encode and base64_decode using javascript. See below links. phpjs.org/functions/base64_encode:358 phpjs.org/functions/base64_decode:357
– gautamlakum
Mar 28 '11 at 13:39
here is another jquery plugin fo base64 encode/decode
– zahid9i
Mar 14 '12 at 18:04
Check microjs: microjs.com/#base64
– Vinod Srivastav
Mar 1 '16 at 14:16
Referenced in meta question Basically identical answers - Only difference: correction of errors.
– Peter Mortensen
Jul 16 '18 at 6:09
2
2
Here is best way to base64_encode and base64_decode using javascript. See below links. phpjs.org/functions/base64_encode:358 phpjs.org/functions/base64_decode:357
– gautamlakum
Mar 28 '11 at 13:39
Here is best way to base64_encode and base64_decode using javascript. See below links. phpjs.org/functions/base64_encode:358 phpjs.org/functions/base64_decode:357
– gautamlakum
Mar 28 '11 at 13:39
here is another jquery plugin fo base64 encode/decode
– zahid9i
Mar 14 '12 at 18:04
here is another jquery plugin fo base64 encode/decode
– zahid9i
Mar 14 '12 at 18:04
Check microjs: microjs.com/#base64
– Vinod Srivastav
Mar 1 '16 at 14:16
Check microjs: microjs.com/#base64
– Vinod Srivastav
Mar 1 '16 at 14:16
Referenced in meta question Basically identical answers - Only difference: correction of errors.
– Peter Mortensen
Jul 16 '18 at 6:09
Referenced in meta question Basically identical answers - Only difference: correction of errors.
– Peter Mortensen
Jul 16 '18 at 6:09
add a comment |
23 Answers
23
active
oldest
votes
You can use btoa()
and atob()
to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between0
and0xff
. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
See also:
- How do I load binary image data using Javascript and XMLHttpRequest?
46
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
5
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
50
you should usebtoa(unescape(encodeURIComponent(str))))
if str is UFT8
– SET
May 15 '13 at 7:49
4
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
|
show 17 more comments
From here:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.
9
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
3
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
18
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
10
All that is needed to make it safe for most binary encoding/decodings it to remove the questionablestring = string.replace(/rn/g,"n");
statement in the utf8 encoding method.
– Marius
Jan 4 '13 at 17:59
4
@Marius: I'm wondering why they would they even includestring = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.
– Triynko
Aug 6 '13 at 22:40
|
show 11 more comments
Internet Explorer 10+
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Cross-Browser
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
jsFiddle
with Node.js
Here is how you encode normal text to base64 in Node.js:
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
with Dojo.js
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str)
bower install angular-base64
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
2
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
add a comment |
Sunny's code is great except it breaks in IE7 because of references to "this". Fixed by replacing such references with "Base64":
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
4
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
add a comment |
You can use btoa
(to base-64) and atob
(from base-64).
For IE 9 and below, try the jquery-base64 plugin:
$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");
126
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
34
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
1
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
9
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 linerbase64.encode(...)
andbase64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...
– Jimbo Jonny
Mar 12 '16 at 5:28
1
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
|
show 3 more comments
There's a couple of bugs in both implementations of _utf8_decode
. c1
and c2
are assigned as global variables due to broken use of the var
statement, and c3
is not initialized or declared at all.
It works, but these variables will overwrite any existing ones with the same name outside this function.
Here's a version that won't do this:
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
}
else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
}
1
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
9
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
2
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
1
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
add a comment |
From the comments (by SET and Stefan Steiger) below the accepted answer, here is a quick summary of how to encode/decode a string to/from base64 without need of a library.
str = "The quick brown fox jumps over the lazy dog";
b64 = btoa(unescape(encodeURIComponent(str)));
str = decodeURIComponent(escape(window.atob(b64)));
Demo
(uses jQuery library, but not for encode/decode)
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
add a comment |
I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely decodeToHex
and encodeFromHex
.
The code:
var Base64 = (function() {
"use strict";
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var _utf8_encode = function (string) {
var utftext = "", c, n;
string = string.replace(/rn/g,"n");
for (n = 0; n < string.length; n++) {
c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var _utf8_decode = function (utftext) {
var string = "", i = 0, c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
};
var _hexEncode = function(input) {
var output = '', i;
for(i = 0; i < input.length; i++) {
output += input.charCodeAt(i).toString(16);
}
return output;
};
var _hexDecode = function(input) {
var output = '', i;
if(input.length % 2 > 0) {
input = '0' + input;
}
for(i = 0; i < input.length; i = i + 2) {
output += String.fromCharCode(parseInt(input.charAt(i) + input.charAt(i + 1), 16));
}
return output;
};
var encode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += _keyStr.charAt(enc1);
output += _keyStr.charAt(enc2);
output += _keyStr.charAt(enc3);
output += _keyStr.charAt(enc4);
}
return output;
};
var decode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
return _utf8_decode(output);
};
var decodeToHex = function(input) {
return _hexEncode(decode(input));
};
var encodeFromHex = function(input) {
return encode(_hexDecode(input));
};
return {
'encode': encode,
'decode': decode,
'decodeToHex': decodeToHex,
'encodeFromHex': encodeFromHex
};
}());
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
add a comment |
To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:
// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';
// make URL friendly:
str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');
// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/
9
I would humbly suggest that the use ofencodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.
– Pablo Fernandez
Oct 28 '11 at 16:22
11
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
add a comment |
I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa
and atob
if they exist due to speed rather than utilize its own encoding:
https://gist.github.com/Nijikokun/5192472
Usage:
base64.encode(/* String */);
base64.decode(/* String */);
utf8.encode(/* String */);
utf8.decode(/* String */);
add a comment |
This question and it's answers pointed me to the right direction.
Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..
Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('n'); // "Cg=="
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "n"
These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.
If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.
add a comment |
Please note that this is not suitable for raw Unicode strings! See Unicode section here.
Syntax for encoding
var encodedData = window.btoa(stringToEncode);
Syntax for decoding
var decodedData = window.atob(encodedData);
add a comment |
if you need to encode HTML image object,
you can write simple function like:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
// escape data:image prefix
return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
// or just return dataURL
// return dataURL
}
To get base64 of image by id:
function getBase64ImageById(id){
return getBase64Image(document.getElementById(id));
}
more here
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
add a comment |
Contributing with a minified polyfill for window.atob
+ window.btoa
that I'm currently using.
(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();
add a comment |
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.
add a comment |
Here is an AngularJS Factory version of @user850789's one:
'use strict';
var ProjectNameBase64Factory = angular.module('project_name.factories.base64', );
ProjectNameBase64Factory.factory('Base64', function () {
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode: function (string) {
string = string.replace(/rn/g, "n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c = 0, c2 = 0, c3 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
return Base64;
});
add a comment |
I needed encoding of an UTF-8 string as base64 for a project of mine. Most of the answers here don't seem to properly handle UTF-16 surrogate pairs when converting to UTF-8 so, for completion sake, I will post my solution:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = ;
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
Note that the code is not thoroughly tested. I tested some inputs, including things like strToUTF8Base64('衠衢蠩蠨')
and compared with the output of an online encoding tool (https://www.base64encode.org/).
add a comment |
For newer browsers to encode Uint8Array to string, and decode string to Uint8Array.
const base64 = {
decode: s => Uint8Array.from(atob(s), c => c.charCodeAt(0)),
encode: b => btoa(String.fromCharCode(...new Uint8Array(b)))
};
For Node.js you can use the following to encode string, Buffer, or Uint8Array to string, and decode from string, Buffer, or Uint8Array to Buffer.
const base64 = {
decode: s => Buffer.from(s, 'base64'),
encode: b => Buffer.from(b).toString('base64')
};
add a comment |
For my project I still need to support IE7 and work with large input to encode.
Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.
Here is the example for encode:
var encode = function (input) {
var output = , chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.push(_keyStr.charAt(enc1));
output.push(_keyStr.charAt(enc2));
output.push(_keyStr.charAt(enc3));
output.push(_keyStr.charAt(enc4));
}
return output.join("");
};
add a comment |
While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.
If you can get your data into a Blob
, then you can use the FileReader.readAsDataURL() function to get a data://
URL and chop off the front of it to get at the base64 data.
You may have to do further processing however to urldecode the data, as I'm not sure whether +
characters are escaped or not for the data://
URL, but this should be pretty trivial.
add a comment |
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
add a comment |
Here is a LIVE DEMO of atob()
and btoa()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
add a comment |
You can use window.btoa
and window.atob
...
const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string
Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:
// ucs-2 string to base64 encoded ascii
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}
// Usage:
utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
utoa('I u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
add a comment |
protected by Robert Levy Jan 6 '14 at 20:45
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
23 Answers
23
active
oldest
votes
23 Answers
23
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use btoa()
and atob()
to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between0
and0xff
. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
See also:
- How do I load binary image data using Javascript and XMLHttpRequest?
46
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
5
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
50
you should usebtoa(unescape(encodeURIComponent(str))))
if str is UFT8
– SET
May 15 '13 at 7:49
4
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
|
show 17 more comments
You can use btoa()
and atob()
to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between0
and0xff
. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
See also:
- How do I load binary image data using Javascript and XMLHttpRequest?
46
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
5
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
50
you should usebtoa(unescape(encodeURIComponent(str))))
if str is UFT8
– SET
May 15 '13 at 7:49
4
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
|
show 17 more comments
You can use btoa()
and atob()
to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between0
and0xff
. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
See also:
- How do I load binary image data using Javascript and XMLHttpRequest?
You can use btoa()
and atob()
to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between0
and0xff
. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
See also:
- How do I load binary image data using Javascript and XMLHttpRequest?
edited Feb 20 at 19:40
Hernán Eche
2,24183863
2,24183863
answered Oct 29 '08 at 15:31
Shog9♦Shog9
129k30209228
129k30209228
46
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
5
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
50
you should usebtoa(unescape(encodeURIComponent(str))))
if str is UFT8
– SET
May 15 '13 at 7:49
4
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
|
show 17 more comments
46
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
5
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
50
you should usebtoa(unescape(encodeURIComponent(str))))
if str is UFT8
– SET
May 15 '13 at 7:49
4
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
46
46
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
Note that this also works for webkit browsers, such as Safari.
– Daniel Von Fange
Sep 2 '10 at 9:59
5
5
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
but it does not work on iPhone3G with iOS 4.1. It does work on the simulator iPhone simulator when set to iPhone4 or iPhone.
– Grant M
Sep 15 '10 at 8:38
23
23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
Please note the special consideration for Unicode strings: developer.mozilla.org/En/DOM/Window.btoa#Unicode_Strings btoa and atob only work properly for ASCII based strings. As an American, you probably won't notice a difference ... but the first time you use an accented character, your code will break.
– Dan Esparza
Nov 8 '11 at 16:23
50
50
you should use
btoa(unescape(encodeURIComponent(str))))
if str is UFT8– SET
May 15 '13 at 7:49
you should use
btoa(unescape(encodeURIComponent(str))))
if str is UFT8– SET
May 15 '13 at 7:49
4
4
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
See my edit, @Triynko. These are not intended to be used to process text, period.
– Shog9♦
Aug 6 '13 at 21:19
|
show 17 more comments
From here:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.
9
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
3
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
18
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
10
All that is needed to make it safe for most binary encoding/decodings it to remove the questionablestring = string.replace(/rn/g,"n");
statement in the utf8 encoding method.
– Marius
Jan 4 '13 at 17:59
4
@Marius: I'm wondering why they would they even includestring = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.
– Triynko
Aug 6 '13 at 22:40
|
show 11 more comments
From here:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.
9
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
3
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
18
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
10
All that is needed to make it safe for most binary encoding/decodings it to remove the questionablestring = string.replace(/rn/g,"n");
statement in the utf8 encoding method.
– Marius
Jan 4 '13 at 17:59
4
@Marius: I'm wondering why they would they even includestring = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.
– Triynko
Aug 6 '13 at 22:40
|
show 11 more comments
From here:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.
From here:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.
edited Dec 13 '12 at 14:02
answered Oct 29 '08 at 13:39
Sunny MilenovSunny Milenov
17.4k46697
17.4k46697
9
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
3
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
18
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
10
All that is needed to make it safe for most binary encoding/decodings it to remove the questionablestring = string.replace(/rn/g,"n");
statement in the utf8 encoding method.
– Marius
Jan 4 '13 at 17:59
4
@Marius: I'm wondering why they would they even includestring = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.
– Triynko
Aug 6 '13 at 22:40
|
show 11 more comments
9
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
3
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
18
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
10
All that is needed to make it safe for most binary encoding/decodings it to remove the questionablestring = string.replace(/rn/g,"n");
statement in the utf8 encoding method.
– Marius
Jan 4 '13 at 17:59
4
@Marius: I'm wondering why they would they even includestring = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.
– Triynko
Aug 6 '13 at 22:40
9
9
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
does this work with <input type="file" /> HTML forms?
– jordan.baucke
Aug 17 '11 at 23:28
3
3
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
This is also useful when the base64 encoding is non-standard; in my case the "/" character wasn't used, and the "?" character was used instead, meaning even in Chrome atob() wasn't going to decode the base64 strings that were incoming.
– Chris Moschini
Dec 17 '11 at 12:43
18
18
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
Be careful with this code - it attempts to interpret your string as a UTF-8 encoded string. We had a case where we had a binary string (i.e. each character in the string should be interpreted as a byte), and this code did corrupt the data. Read the source, Luke.
– Daniel Yankowsky
Nov 12 '12 at 18:27
10
10
All that is needed to make it safe for most binary encoding/decodings it to remove the questionable
string = string.replace(/rn/g,"n");
statement in the utf8 encoding method.– Marius
Jan 4 '13 at 17:59
All that is needed to make it safe for most binary encoding/decodings it to remove the questionable
string = string.replace(/rn/g,"n");
statement in the utf8 encoding method.– Marius
Jan 4 '13 at 17:59
4
4
@Marius: I'm wondering why they would they even include
string = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.– Triynko
Aug 6 '13 at 22:40
@Marius: I'm wondering why they would they even include
string = string.replace(/rn/g,"n");
in the first place, lol. It's like "oh, lets encode this string, but first, why don't we just randomly normalize all the line breaks for no good reason at all". That should absolutely be removed from the class under all circumstances.– Triynko
Aug 6 '13 at 22:40
|
show 11 more comments
Internet Explorer 10+
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Cross-Browser
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
jsFiddle
with Node.js
Here is how you encode normal text to base64 in Node.js:
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
with Dojo.js
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str)
bower install angular-base64
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
2
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
add a comment |
Internet Explorer 10+
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Cross-Browser
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
jsFiddle
with Node.js
Here is how you encode normal text to base64 in Node.js:
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
with Dojo.js
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str)
bower install angular-base64
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
2
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
add a comment |
Internet Explorer 10+
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Cross-Browser
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
jsFiddle
with Node.js
Here is how you encode normal text to base64 in Node.js:
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
with Dojo.js
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str)
bower install angular-base64
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
Internet Explorer 10+
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Cross-Browser
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
jsFiddle
with Node.js
Here is how you encode normal text to base64 in Node.js:
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
with Dojo.js
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str)
bower install angular-base64
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
answered Oct 22 '14 at 18:06
davidcondreydavidcondrey
22.8k680117
22.8k680117
2
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
add a comment |
2
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
2
2
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
This answer is based on the original code and DOES NOT include updates to that code posted in other answers here.
– Eugene Ryabtsev
Nov 27 '14 at 10:15
add a comment |
Sunny's code is great except it breaks in IE7 because of references to "this". Fixed by replacing such references with "Base64":
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
4
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
add a comment |
Sunny's code is great except it breaks in IE7 because of references to "this". Fixed by replacing such references with "Base64":
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
4
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
add a comment |
Sunny's code is great except it breaks in IE7 because of references to "this". Fixed by replacing such references with "Base64":
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
Sunny's code is great except it breaks in IE7 because of references to "this". Fixed by replacing such references with "Base64":
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
answered Jul 18 '11 at 22:08
user850789user850789
92162
92162
4
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
add a comment |
4
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
4
4
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
ooh my bad, I was taking the input from browser URL; where | is converted to %7C; hence the encoding also wrong.
– Kanagavelu Sugumar
Sep 11 '13 at 8:03
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
I know this is really old, but I have seen this function used in more than one place, the key string is actually at 65 characters, not 64. The string is not standard spec, I am not sure it matters, but was just wondering if it does?
– Jonathan Wagner
Jun 17 '15 at 4:17
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
"use strict"; is what breaks the 'this' and other type elements like 'with' and from what I have read, 'eval' gets a bashing. All misplaced ideas on abuse. Personally I do not see why JavaScript needs to go down the route its going, it was never meant to be a program tightly bound and made more complex than it is already. If you want to be bound then make a compiler for javascript.
– Mark Giblin
Oct 10 '15 at 12:30
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
I try to use this function and I receive the error: Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object teste teste teste I'm trying to encode .txt with "teste teste teste". Anyone knows why this error?
– PRVS
Nov 4 '15 at 9:19
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
@JonathanWagner - there are 64 characters used for the normal encoding. The 65th character is used as padding them the input string does not have a number of characters divisible by 3.
– Kickstart
Sep 5 '17 at 13:58
add a comment |
You can use btoa
(to base-64) and atob
(from base-64).
For IE 9 and below, try the jquery-base64 plugin:
$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");
126
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
34
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
1
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
9
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 linerbase64.encode(...)
andbase64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...
– Jimbo Jonny
Mar 12 '16 at 5:28
1
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
|
show 3 more comments
You can use btoa
(to base-64) and atob
(from base-64).
For IE 9 and below, try the jquery-base64 plugin:
$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");
126
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
34
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
1
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
9
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 linerbase64.encode(...)
andbase64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...
– Jimbo Jonny
Mar 12 '16 at 5:28
1
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
|
show 3 more comments
You can use btoa
(to base-64) and atob
(from base-64).
For IE 9 and below, try the jquery-base64 plugin:
$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");
You can use btoa
(to base-64) and atob
(from base-64).
For IE 9 and below, try the jquery-base64 plugin:
$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");
edited Dec 1 '14 at 12:44
answered Dec 27 '11 at 3:27
Vitalii FedorenkoVitalii Fedorenko
71.2k21135107
71.2k21135107
126
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
34
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
1
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
9
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 linerbase64.encode(...)
andbase64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...
– Jimbo Jonny
Mar 12 '16 at 5:28
1
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
|
show 3 more comments
126
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
34
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
1
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
9
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 linerbase64.encode(...)
andbase64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...
– Jimbo Jonny
Mar 12 '16 at 5:28
1
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
126
126
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
Why does everything need to be a jQuery plugin :c this is just core JavaScript functionality this has nothing to do with the DOM or jQuery
– EaterOfCode
Apr 29 '13 at 11:04
34
34
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
This is not a core functionality or there wouldn't be as many different high voted answers (including do-it-yourself tl;dr code). So, imho this is actually a good use case for jQuery (one liner, expected to work even in Android's WebView) - even more if it's already a dependency.
– Risadinha
Aug 26 '13 at 17:04
1
1
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
I like to install code snippets like this into jQuery mainly because they'll exist in a controlled namespace. If you're not using AMD or CommonJS or a similar design pattern, it's easy for your global namespace to get really messy with a bunch of random functions.
– sffc
Jun 25 '14 at 7:23
9
9
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 liner
base64.encode(...)
and base64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...– Jimbo Jonny
Mar 12 '16 at 5:28
@Risadinha - except its functionality does not depend on or extend anything jQuery at all...literally the only references to jQuery in its code are attaching it to the jQuery object...so what's the point in attaching it to jQuery and therefore requiring jQuery to use? Just make it it's own 1 liner
base64.encode(...)
and base64.decode(...)
...attaching it to jQuery when it has zero jQuery specific functionality makes absolutely no sense...– Jimbo Jonny
Mar 12 '16 at 5:28
1
1
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
jQuery was not requested. Not a valid answer to a plain old JS question.
– metaColin
Feb 10 '17 at 22:20
|
show 3 more comments
There's a couple of bugs in both implementations of _utf8_decode
. c1
and c2
are assigned as global variables due to broken use of the var
statement, and c3
is not initialized or declared at all.
It works, but these variables will overwrite any existing ones with the same name outside this function.
Here's a version that won't do this:
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
}
else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
}
1
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
9
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
2
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
1
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
add a comment |
There's a couple of bugs in both implementations of _utf8_decode
. c1
and c2
are assigned as global variables due to broken use of the var
statement, and c3
is not initialized or declared at all.
It works, but these variables will overwrite any existing ones with the same name outside this function.
Here's a version that won't do this:
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
}
else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
}
1
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
9
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
2
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
1
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
add a comment |
There's a couple of bugs in both implementations of _utf8_decode
. c1
and c2
are assigned as global variables due to broken use of the var
statement, and c3
is not initialized or declared at all.
It works, but these variables will overwrite any existing ones with the same name outside this function.
Here's a version that won't do this:
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
}
else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
}
There's a couple of bugs in both implementations of _utf8_decode
. c1
and c2
are assigned as global variables due to broken use of the var
statement, and c3
is not initialized or declared at all.
It works, but these variables will overwrite any existing ones with the same name outside this function.
Here's a version that won't do this:
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
}
else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
}
answered Jul 26 '11 at 21:14
robblesrobbles
1,89011827
1,89011827
1
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
9
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
2
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
1
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
add a comment |
1
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
9
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
2
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
1
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
1
1
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
Why don't you just update the previous answer?
– Daan
Dec 9 '13 at 15:52
9
9
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
@Daan I didn't have enough rep to edit answers when I wrote this answer...in 2011.
– robbles
Dec 10 '13 at 17:42
2
2
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
IE7 ? i guess we should stop wasting time to write code for that, people won't stop using this old technology unless we developers forced them to!
– Ronan Dejhero
Jun 7 '14 at 15:01
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
@RonanDejhero does it not work in IE7? I don't remember if I tested in that particular browser.
– robbles
Jun 8 '14 at 22:47
1
1
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
What i meant that if it does not work in IE7, no one should care!. i didn't test and won't test it :)
– Ronan Dejhero
Jun 9 '14 at 11:02
add a comment |
From the comments (by SET and Stefan Steiger) below the accepted answer, here is a quick summary of how to encode/decode a string to/from base64 without need of a library.
str = "The quick brown fox jumps over the lazy dog";
b64 = btoa(unescape(encodeURIComponent(str)));
str = decodeURIComponent(escape(window.atob(b64)));
Demo
(uses jQuery library, but not for encode/decode)
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
add a comment |
From the comments (by SET and Stefan Steiger) below the accepted answer, here is a quick summary of how to encode/decode a string to/from base64 without need of a library.
str = "The quick brown fox jumps over the lazy dog";
b64 = btoa(unescape(encodeURIComponent(str)));
str = decodeURIComponent(escape(window.atob(b64)));
Demo
(uses jQuery library, but not for encode/decode)
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
add a comment |
From the comments (by SET and Stefan Steiger) below the accepted answer, here is a quick summary of how to encode/decode a string to/from base64 without need of a library.
str = "The quick brown fox jumps over the lazy dog";
b64 = btoa(unescape(encodeURIComponent(str)));
str = decodeURIComponent(escape(window.atob(b64)));
Demo
(uses jQuery library, but not for encode/decode)
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
From the comments (by SET and Stefan Steiger) below the accepted answer, here is a quick summary of how to encode/decode a string to/from base64 without need of a library.
str = "The quick brown fox jumps over the lazy dog";
b64 = btoa(unescape(encodeURIComponent(str)));
str = decodeURIComponent(escape(window.atob(b64)));
Demo
(uses jQuery library, but not for encode/decode)
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
str = "The quick brown fox jumps over the lazy dog";
$('input').val(str);
$('#btnConv').click(function(){
var txt = $('input').val();
var b64 = btoa(unescape(encodeURIComponent(txt)));
$('input').val(b64);
$('#btnDeConv').show();
});
$('#btnDeConv').click(function(){
var b64 = $('input').val();
var txt = decodeURIComponent(escape(window.atob(b64)));
$('input').val(txt);
});
#btnDeConv{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="btnConv">Convert</button>
<button id="btnDeConv">DeConvert</button>
edited Feb 3 '18 at 9:10
Crashalot
15.3k48189330
15.3k48189330
answered Aug 23 '17 at 16:24
crashwapcrashwap
1,21411529
1,21411529
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
add a comment |
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
To confirm, this supports UTF-8 characters?
– Crashalot
Feb 3 '18 at 9:09
add a comment |
I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely decodeToHex
and encodeFromHex
.
The code:
var Base64 = (function() {
"use strict";
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var _utf8_encode = function (string) {
var utftext = "", c, n;
string = string.replace(/rn/g,"n");
for (n = 0; n < string.length; n++) {
c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var _utf8_decode = function (utftext) {
var string = "", i = 0, c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
};
var _hexEncode = function(input) {
var output = '', i;
for(i = 0; i < input.length; i++) {
output += input.charCodeAt(i).toString(16);
}
return output;
};
var _hexDecode = function(input) {
var output = '', i;
if(input.length % 2 > 0) {
input = '0' + input;
}
for(i = 0; i < input.length; i = i + 2) {
output += String.fromCharCode(parseInt(input.charAt(i) + input.charAt(i + 1), 16));
}
return output;
};
var encode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += _keyStr.charAt(enc1);
output += _keyStr.charAt(enc2);
output += _keyStr.charAt(enc3);
output += _keyStr.charAt(enc4);
}
return output;
};
var decode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
return _utf8_decode(output);
};
var decodeToHex = function(input) {
return _hexEncode(decode(input));
};
var encodeFromHex = function(input) {
return encode(_hexDecode(input));
};
return {
'encode': encode,
'decode': decode,
'decodeToHex': decodeToHex,
'encodeFromHex': encodeFromHex
};
}());
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
add a comment |
I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely decodeToHex
and encodeFromHex
.
The code:
var Base64 = (function() {
"use strict";
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var _utf8_encode = function (string) {
var utftext = "", c, n;
string = string.replace(/rn/g,"n");
for (n = 0; n < string.length; n++) {
c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var _utf8_decode = function (utftext) {
var string = "", i = 0, c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
};
var _hexEncode = function(input) {
var output = '', i;
for(i = 0; i < input.length; i++) {
output += input.charCodeAt(i).toString(16);
}
return output;
};
var _hexDecode = function(input) {
var output = '', i;
if(input.length % 2 > 0) {
input = '0' + input;
}
for(i = 0; i < input.length; i = i + 2) {
output += String.fromCharCode(parseInt(input.charAt(i) + input.charAt(i + 1), 16));
}
return output;
};
var encode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += _keyStr.charAt(enc1);
output += _keyStr.charAt(enc2);
output += _keyStr.charAt(enc3);
output += _keyStr.charAt(enc4);
}
return output;
};
var decode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
return _utf8_decode(output);
};
var decodeToHex = function(input) {
return _hexEncode(decode(input));
};
var encodeFromHex = function(input) {
return encode(_hexDecode(input));
};
return {
'encode': encode,
'decode': decode,
'decodeToHex': decodeToHex,
'encodeFromHex': encodeFromHex
};
}());
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
add a comment |
I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely decodeToHex
and encodeFromHex
.
The code:
var Base64 = (function() {
"use strict";
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var _utf8_encode = function (string) {
var utftext = "", c, n;
string = string.replace(/rn/g,"n");
for (n = 0; n < string.length; n++) {
c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var _utf8_decode = function (utftext) {
var string = "", i = 0, c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
};
var _hexEncode = function(input) {
var output = '', i;
for(i = 0; i < input.length; i++) {
output += input.charCodeAt(i).toString(16);
}
return output;
};
var _hexDecode = function(input) {
var output = '', i;
if(input.length % 2 > 0) {
input = '0' + input;
}
for(i = 0; i < input.length; i = i + 2) {
output += String.fromCharCode(parseInt(input.charAt(i) + input.charAt(i + 1), 16));
}
return output;
};
var encode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += _keyStr.charAt(enc1);
output += _keyStr.charAt(enc2);
output += _keyStr.charAt(enc3);
output += _keyStr.charAt(enc4);
}
return output;
};
var decode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
return _utf8_decode(output);
};
var decodeToHex = function(input) {
return _hexEncode(decode(input));
};
var encodeFromHex = function(input) {
return encode(_hexDecode(input));
};
return {
'encode': encode,
'decode': decode,
'decodeToHex': decodeToHex,
'encodeFromHex': encodeFromHex
};
}());
I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely decodeToHex
and encodeFromHex
.
The code:
var Base64 = (function() {
"use strict";
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var _utf8_encode = function (string) {
var utftext = "", c, n;
string = string.replace(/rn/g,"n");
for (n = 0; n < string.length; n++) {
c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var _utf8_decode = function (utftext) {
var string = "", i = 0, c = 0, c1 = 0, c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i+1);
c2 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
};
var _hexEncode = function(input) {
var output = '', i;
for(i = 0; i < input.length; i++) {
output += input.charCodeAt(i).toString(16);
}
return output;
};
var _hexDecode = function(input) {
var output = '', i;
if(input.length % 2 > 0) {
input = '0' + input;
}
for(i = 0; i < input.length; i = i + 2) {
output += String.fromCharCode(parseInt(input.charAt(i) + input.charAt(i + 1), 16));
}
return output;
};
var encode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += _keyStr.charAt(enc1);
output += _keyStr.charAt(enc2);
output += _keyStr.charAt(enc3);
output += _keyStr.charAt(enc4);
}
return output;
};
var decode = function (input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
return _utf8_decode(output);
};
var decodeToHex = function(input) {
return _hexEncode(decode(input));
};
var encodeFromHex = function(input) {
return encode(_hexDecode(input));
};
return {
'encode': encode,
'decode': decode,
'decodeToHex': decodeToHex,
'encodeFromHex': encodeFromHex
};
}());
answered Aug 20 '12 at 16:07
Joe DyndaleJoe Dyndale
84511229
84511229
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
add a comment |
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I initially thought your unrolling of the output concatenation into separate statements would be more optimal, but after I thought about it for a sec, this should be more inefficient since Javascript strings are immutable and it would cause 4 copies of potentially huge data blobs when working with large binary data files. It is a safer bet to concatenate the 4 chars together first and then building a new string. I wish I knew for certain of a better string building method that would be sure to be efficient on all platforms. (even IE6)
– Marius
Jan 4 '13 at 18:19
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
I haven't considered performance in my cleanup of the originally posted code. I just made it more readable and made methods marked as private in the comments in the original actually be private by using the revealing module pattern. I'm sure it can be optimized in regards to performance as well. Not quite sure when garbage collection would kick in here, and hashing large files through Javascript isn't very common (or indeed likely not the optimal solution in any case).
– Joe Dyndale
Jan 7 '13 at 11:39
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
Funny how this code sort of lives here. There are already 3 different versions of it on this page.
– gregn3
Mar 7 '14 at 12:37
add a comment |
To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:
// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';
// make URL friendly:
str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');
// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/
9
I would humbly suggest that the use ofencodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.
– Pablo Fernandez
Oct 28 '11 at 16:22
11
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
add a comment |
To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:
// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';
// make URL friendly:
str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');
// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/
9
I would humbly suggest that the use ofencodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.
– Pablo Fernandez
Oct 28 '11 at 16:22
11
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
add a comment |
To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:
// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';
// make URL friendly:
str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');
// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/
To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:
// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';
// make URL friendly:
str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');
// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/
answered Aug 21 '11 at 15:07
magikMakermagikMaker
1,0581112
1,0581112
9
I would humbly suggest that the use ofencodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.
– Pablo Fernandez
Oct 28 '11 at 16:22
11
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
add a comment |
9
I would humbly suggest that the use ofencodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.
– Pablo Fernandez
Oct 28 '11 at 16:22
11
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
9
9
I would humbly suggest that the use of
encodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.– Pablo Fernandez
Oct 28 '11 at 16:22
I would humbly suggest that the use of
encodeURIComponent
may well result in a superior outcome with less expenditure of effort on the part of the developer.– Pablo Fernandez
Oct 28 '11 at 16:22
11
11
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
encodeURIComponent will change the length of base64 encoded strings, and replacing '-' and '_' with '+' and '/' is standard practice when using base64 in URLs (e.g. docs.python.org/library/base64.html#base64.urlsafe_b64encode). No need to get upset.
– natevw
Dec 22 '11 at 17:29
add a comment |
I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa
and atob
if they exist due to speed rather than utilize its own encoding:
https://gist.github.com/Nijikokun/5192472
Usage:
base64.encode(/* String */);
base64.decode(/* String */);
utf8.encode(/* String */);
utf8.decode(/* String */);
add a comment |
I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa
and atob
if they exist due to speed rather than utilize its own encoding:
https://gist.github.com/Nijikokun/5192472
Usage:
base64.encode(/* String */);
base64.decode(/* String */);
utf8.encode(/* String */);
utf8.decode(/* String */);
add a comment |
I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa
and atob
if they exist due to speed rather than utilize its own encoding:
https://gist.github.com/Nijikokun/5192472
Usage:
base64.encode(/* String */);
base64.decode(/* String */);
utf8.encode(/* String */);
utf8.decode(/* String */);
I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa
and atob
if they exist due to speed rather than utilize its own encoding:
https://gist.github.com/Nijikokun/5192472
Usage:
base64.encode(/* String */);
base64.decode(/* String */);
utf8.encode(/* String */);
utf8.decode(/* String */);
answered Mar 19 '13 at 0:56
NijikokunNijikokun
1,1961222
1,1961222
add a comment |
add a comment |
This question and it's answers pointed me to the right direction.
Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..
Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('n'); // "Cg=="
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "n"
These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.
If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.
add a comment |
This question and it's answers pointed me to the right direction.
Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..
Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('n'); // "Cg=="
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "n"
These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.
If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.
add a comment |
This question and it's answers pointed me to the right direction.
Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..
Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('n'); // "Cg=="
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "n"
These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.
If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.
This question and it's answers pointed me to the right direction.
Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..
Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('n'); // "Cg=="
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "n"
These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.
If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.
answered Nov 3 '16 at 2:24
JohnJohn
4,44313542
4,44313542
add a comment |
add a comment |
Please note that this is not suitable for raw Unicode strings! See Unicode section here.
Syntax for encoding
var encodedData = window.btoa(stringToEncode);
Syntax for decoding
var decodedData = window.atob(encodedData);
add a comment |
Please note that this is not suitable for raw Unicode strings! See Unicode section here.
Syntax for encoding
var encodedData = window.btoa(stringToEncode);
Syntax for decoding
var decodedData = window.atob(encodedData);
add a comment |
Please note that this is not suitable for raw Unicode strings! See Unicode section here.
Syntax for encoding
var encodedData = window.btoa(stringToEncode);
Syntax for decoding
var decodedData = window.atob(encodedData);
Please note that this is not suitable for raw Unicode strings! See Unicode section here.
Syntax for encoding
var encodedData = window.btoa(stringToEncode);
Syntax for decoding
var decodedData = window.atob(encodedData);
answered Feb 4 '13 at 12:39
KathirKathir
9531320
9531320
add a comment |
add a comment |
if you need to encode HTML image object,
you can write simple function like:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
// escape data:image prefix
return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
// or just return dataURL
// return dataURL
}
To get base64 of image by id:
function getBase64ImageById(id){
return getBase64Image(document.getElementById(id));
}
more here
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
add a comment |
if you need to encode HTML image object,
you can write simple function like:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
// escape data:image prefix
return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
// or just return dataURL
// return dataURL
}
To get base64 of image by id:
function getBase64ImageById(id){
return getBase64Image(document.getElementById(id));
}
more here
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
add a comment |
if you need to encode HTML image object,
you can write simple function like:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
// escape data:image prefix
return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
// or just return dataURL
// return dataURL
}
To get base64 of image by id:
function getBase64ImageById(id){
return getBase64Image(document.getElementById(id));
}
more here
if you need to encode HTML image object,
you can write simple function like:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
// escape data:image prefix
return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
// or just return dataURL
// return dataURL
}
To get base64 of image by id:
function getBase64ImageById(id){
return getBase64Image(document.getElementById(id));
}
more here
answered Jan 12 '13 at 22:28
NedudiNedudi
3,83912829
3,83912829
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
add a comment |
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
Yep, and var img = new Image(); img.src = "../images/myPic.png";
– pdschuller
Dec 10 '13 at 18:01
add a comment |
Contributing with a minified polyfill for window.atob
+ window.btoa
that I'm currently using.
(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();
add a comment |
Contributing with a minified polyfill for window.atob
+ window.btoa
that I'm currently using.
(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();
add a comment |
Contributing with a minified polyfill for window.atob
+ window.btoa
that I'm currently using.
(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();
Contributing with a minified polyfill for window.atob
+ window.btoa
that I'm currently using.
(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();
answered Nov 20 '13 at 8:24
JohanJohan
16.2k38141244
16.2k38141244
add a comment |
add a comment |
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.
add a comment |
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.
add a comment |
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.
answered Nov 17 '13 at 7:05
Dan DascalescuDan Dascalescu
68.4k21206276
68.4k21206276
add a comment |
add a comment |
Here is an AngularJS Factory version of @user850789's one:
'use strict';
var ProjectNameBase64Factory = angular.module('project_name.factories.base64', );
ProjectNameBase64Factory.factory('Base64', function () {
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode: function (string) {
string = string.replace(/rn/g, "n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c = 0, c2 = 0, c3 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
return Base64;
});
add a comment |
Here is an AngularJS Factory version of @user850789's one:
'use strict';
var ProjectNameBase64Factory = angular.module('project_name.factories.base64', );
ProjectNameBase64Factory.factory('Base64', function () {
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode: function (string) {
string = string.replace(/rn/g, "n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c = 0, c2 = 0, c3 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
return Base64;
});
add a comment |
Here is an AngularJS Factory version of @user850789's one:
'use strict';
var ProjectNameBase64Factory = angular.module('project_name.factories.base64', );
ProjectNameBase64Factory.factory('Base64', function () {
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode: function (string) {
string = string.replace(/rn/g, "n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c = 0, c2 = 0, c3 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
return Base64;
});
Here is an AngularJS Factory version of @user850789's one:
'use strict';
var ProjectNameBase64Factory = angular.module('project_name.factories.base64', );
ProjectNameBase64Factory.factory('Base64', function () {
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode: function (string) {
string = string.replace(/rn/g, "n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c = 0, c2 = 0, c3 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
return Base64;
});
answered May 25 '14 at 4:27
A TA T
5,4281060105
5,4281060105
add a comment |
add a comment |
I needed encoding of an UTF-8 string as base64 for a project of mine. Most of the answers here don't seem to properly handle UTF-16 surrogate pairs when converting to UTF-8 so, for completion sake, I will post my solution:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = ;
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
Note that the code is not thoroughly tested. I tested some inputs, including things like strToUTF8Base64('衠衢蠩蠨')
and compared with the output of an online encoding tool (https://www.base64encode.org/).
add a comment |
I needed encoding of an UTF-8 string as base64 for a project of mine. Most of the answers here don't seem to properly handle UTF-16 surrogate pairs when converting to UTF-8 so, for completion sake, I will post my solution:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = ;
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
Note that the code is not thoroughly tested. I tested some inputs, including things like strToUTF8Base64('衠衢蠩蠨')
and compared with the output of an online encoding tool (https://www.base64encode.org/).
add a comment |
I needed encoding of an UTF-8 string as base64 for a project of mine. Most of the answers here don't seem to properly handle UTF-16 surrogate pairs when converting to UTF-8 so, for completion sake, I will post my solution:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = ;
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
Note that the code is not thoroughly tested. I tested some inputs, including things like strToUTF8Base64('衠衢蠩蠨')
and compared with the output of an online encoding tool (https://www.base64encode.org/).
I needed encoding of an UTF-8 string as base64 for a project of mine. Most of the answers here don't seem to properly handle UTF-16 surrogate pairs when converting to UTF-8 so, for completion sake, I will post my solution:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = ;
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
Note that the code is not thoroughly tested. I tested some inputs, including things like strToUTF8Base64('衠衢蠩蠨')
and compared with the output of an online encoding tool (https://www.base64encode.org/).
answered Oct 4 '14 at 18:34
Ricardo MachadoRicardo Machado
17924
17924
add a comment |
add a comment |
For newer browsers to encode Uint8Array to string, and decode string to Uint8Array.
const base64 = {
decode: s => Uint8Array.from(atob(s), c => c.charCodeAt(0)),
encode: b => btoa(String.fromCharCode(...new Uint8Array(b)))
};
For Node.js you can use the following to encode string, Buffer, or Uint8Array to string, and decode from string, Buffer, or Uint8Array to Buffer.
const base64 = {
decode: s => Buffer.from(s, 'base64'),
encode: b => Buffer.from(b).toString('base64')
};
add a comment |
For newer browsers to encode Uint8Array to string, and decode string to Uint8Array.
const base64 = {
decode: s => Uint8Array.from(atob(s), c => c.charCodeAt(0)),
encode: b => btoa(String.fromCharCode(...new Uint8Array(b)))
};
For Node.js you can use the following to encode string, Buffer, or Uint8Array to string, and decode from string, Buffer, or Uint8Array to Buffer.
const base64 = {
decode: s => Buffer.from(s, 'base64'),
encode: b => Buffer.from(b).toString('base64')
};
add a comment |
For newer browsers to encode Uint8Array to string, and decode string to Uint8Array.
const base64 = {
decode: s => Uint8Array.from(atob(s), c => c.charCodeAt(0)),
encode: b => btoa(String.fromCharCode(...new Uint8Array(b)))
};
For Node.js you can use the following to encode string, Buffer, or Uint8Array to string, and decode from string, Buffer, or Uint8Array to Buffer.
const base64 = {
decode: s => Buffer.from(s, 'base64'),
encode: b => Buffer.from(b).toString('base64')
};
For newer browsers to encode Uint8Array to string, and decode string to Uint8Array.
const base64 = {
decode: s => Uint8Array.from(atob(s), c => c.charCodeAt(0)),
encode: b => btoa(String.fromCharCode(...new Uint8Array(b)))
};
For Node.js you can use the following to encode string, Buffer, or Uint8Array to string, and decode from string, Buffer, or Uint8Array to Buffer.
const base64 = {
decode: s => Buffer.from(s, 'base64'),
encode: b => Buffer.from(b).toString('base64')
};
answered Nov 9 '18 at 7:15
RixRix
833814
833814
add a comment |
add a comment |
For my project I still need to support IE7 and work with large input to encode.
Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.
Here is the example for encode:
var encode = function (input) {
var output = , chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.push(_keyStr.charAt(enc1));
output.push(_keyStr.charAt(enc2));
output.push(_keyStr.charAt(enc3));
output.push(_keyStr.charAt(enc4));
}
return output.join("");
};
add a comment |
For my project I still need to support IE7 and work with large input to encode.
Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.
Here is the example for encode:
var encode = function (input) {
var output = , chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.push(_keyStr.charAt(enc1));
output.push(_keyStr.charAt(enc2));
output.push(_keyStr.charAt(enc3));
output.push(_keyStr.charAt(enc4));
}
return output.join("");
};
add a comment |
For my project I still need to support IE7 and work with large input to encode.
Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.
Here is the example for encode:
var encode = function (input) {
var output = , chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.push(_keyStr.charAt(enc1));
output.push(_keyStr.charAt(enc2));
output.push(_keyStr.charAt(enc3));
output.push(_keyStr.charAt(enc4));
}
return output.join("");
};
For my project I still need to support IE7 and work with large input to encode.
Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.
Here is the example for encode:
var encode = function (input) {
var output = , chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.push(_keyStr.charAt(enc1));
output.push(_keyStr.charAt(enc2));
output.push(_keyStr.charAt(enc3));
output.push(_keyStr.charAt(enc4));
}
return output.join("");
};
answered Jul 24 '13 at 6:52
NicoNico
4912
4912
add a comment |
add a comment |
While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.
If you can get your data into a Blob
, then you can use the FileReader.readAsDataURL() function to get a data://
URL and chop off the front of it to get at the base64 data.
You may have to do further processing however to urldecode the data, as I'm not sure whether +
characters are escaped or not for the data://
URL, but this should be pretty trivial.
add a comment |
While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.
If you can get your data into a Blob
, then you can use the FileReader.readAsDataURL() function to get a data://
URL and chop off the front of it to get at the base64 data.
You may have to do further processing however to urldecode the data, as I'm not sure whether +
characters are escaped or not for the data://
URL, but this should be pretty trivial.
add a comment |
While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.
If you can get your data into a Blob
, then you can use the FileReader.readAsDataURL() function to get a data://
URL and chop off the front of it to get at the base64 data.
You may have to do further processing however to urldecode the data, as I'm not sure whether +
characters are escaped or not for the data://
URL, but this should be pretty trivial.
While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.
If you can get your data into a Blob
, then you can use the FileReader.readAsDataURL() function to get a data://
URL and chop off the front of it to get at the base64 data.
You may have to do further processing however to urldecode the data, as I'm not sure whether +
characters are escaped or not for the data://
URL, but this should be pretty trivial.
answered Jul 21 '16 at 1:11
MalvineousMalvineous
11.6k97899
11.6k97899
add a comment |
add a comment |
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
add a comment |
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
add a comment |
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
edited Jul 18 '18 at 13:12
Camilo Terevinto
18.9k63767
18.9k63767
answered Aug 29 '13 at 14:10
Vikash PandeyVikash Pandey
4,24362934
4,24362934
add a comment |
add a comment |
Here is a LIVE DEMO of atob()
and btoa()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
add a comment |
Here is a LIVE DEMO of atob()
and btoa()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
add a comment |
Here is a LIVE DEMO of atob()
and btoa()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
Here is a LIVE DEMO of atob()
and btoa()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
answered Feb 9 at 10:20
jonathanajonathana
3,22921227
3,22921227
add a comment |
add a comment |
You can use window.btoa
and window.atob
...
const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string
Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:
// ucs-2 string to base64 encoded ascii
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}
// Usage:
utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
utoa('I u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
add a comment |
You can use window.btoa
and window.atob
...
const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string
Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:
// ucs-2 string to base64 encoded ascii
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}
// Usage:
utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
utoa('I u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
add a comment |
You can use window.btoa
and window.atob
...
const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string
Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:
// ucs-2 string to base64 encoded ascii
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}
// Usage:
utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
utoa('I u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
You can use window.btoa
and window.atob
...
const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string
Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:
// ucs-2 string to base64 encoded ascii
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}
// Usage:
utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
utoa('I u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
answered Oct 15 '18 at 11:23
AlirezaAlireza
50.4k13173123
50.4k13173123
add a comment |
add a comment |
protected by Robert Levy Jan 6 '14 at 20:45
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
2
Here is best way to base64_encode and base64_decode using javascript. See below links. phpjs.org/functions/base64_encode:358 phpjs.org/functions/base64_decode:357
– gautamlakum
Mar 28 '11 at 13:39
here is another jquery plugin fo base64 encode/decode
– zahid9i
Mar 14 '12 at 18:04
Check microjs: microjs.com/#base64
– Vinod Srivastav
Mar 1 '16 at 14:16
Referenced in meta question Basically identical answers - Only difference: correction of errors.
– Peter Mortensen
Jul 16 '18 at 6:09