@@ -7,16 +7,30 @@ module.exports = function base64_encode (stringToEncode) { // eslint-disable-lin
7
7
// improved by: Kevin van Zonneveld (http://kvz.io)
8
8
// improved by: Rafał Kukawski (http://blog.kukawski.pl)
9
9
// bugfixed by: Pellentesque Malesuada
10
+ // improved by: Indigo744
10
11
// example 1: base64_encode('Kevin van Zonneveld')
11
12
// returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
12
13
// example 2: base64_encode('a')
13
14
// returns 2: 'YQ=='
14
15
// example 3: base64_encode('✓ à la mode')
15
16
// returns 3: '4pyTIMOgIGxhIG1vZGU='
16
17
18
+ // encodeUTF8string()
19
+ // Internal function to encode properly UTF8 string
20
+ // Adapted from Solution #1 at https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
21
+ var encodeUTF8string = function ( str ) {
22
+ // first we use encodeURIComponent to get percent-encoded UTF-8,
23
+ // then we convert the percent encodings into raw bytes which
24
+ // can be fed into the base64 encoding algorithm.
25
+ return encodeURIComponent ( str ) . replace ( / % ( [ 0 - 9 A - F ] { 2 } ) / g,
26
+ function toSolidBytes ( match , p1 ) {
27
+ return String . fromCharCode ( '0x' + p1 )
28
+ } )
29
+ }
30
+
17
31
if ( typeof window !== 'undefined' ) {
18
32
if ( typeof window . btoa !== 'undefined' ) {
19
- return window . btoa ( decodeURIComponent ( encodeURIComponent ( stringToEncode ) ) )
33
+ return window . btoa ( encodeUTF8string ( stringToEncode ) )
20
34
}
21
35
} else {
22
36
return new Buffer ( stringToEncode ) . toString ( 'base64' )
@@ -40,7 +54,7 @@ module.exports = function base64_encode (stringToEncode) { // eslint-disable-lin
40
54
return stringToEncode
41
55
}
42
56
43
- stringToEncode = decodeURIComponent ( encodeURIComponent ( stringToEncode ) )
57
+ stringToEncode = encodeUTF8string ( stringToEncode )
44
58
45
59
do {
46
60
// pack three octets into four hexets
0 commit comments