How can we support special characters in react native base 64?
import base from 'react-native-base64'
....
base.encode(str)
....
str would be asdĞ or any other special characters from some languages.
I have used this package https://www.npmjs.com/package/react-native-base64
Currently while decoding it converting the string to asd
Here is the example code
import React from "react";
import { View, Text } from "react-native";
import base from "react-native-base64";
const Decode = () => {
const string = "asdĞ";
const encode = base.encode(string);
const decode = base.decode(encode);
return (
<View>
<Text>{"String = " + string}</Text>
<Text>{"DecodeS = " + decode}</Text>
</View>
);
};
export default Decode;
you can try it on https://codesandbox.io/s/aged-currying-te3ki4?file=/src/Decode.js
This can be solved by using encodeURIComponent
before you encode to Base64 and the counterpart decodeURIComponent
after decoding from Base64
The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
This solution was proposed here and I found that page by reading this answer (this answer did not directly answer the above question and the proposed solution in it did not work for me). It's recommended to read the whole linked page to understand the problem and the possible solutions.
import React from "react";
import { View, Text } from "react-native";
import base from "react-native-base64";
function b64EncodeUnicode(str) {
return base.encode(encodeURIComponent(str));
}
function UnicodeDecodeB64(str) {
return decodeURIComponent(base.decode(str));
}
const Decode = () => {
const string = "asdĞ";
//const encode = base.encode(string);
const encode = b64EncodeUnicode(string);
const decode = UnicodeDecodeB64(encode);
return (
<View>
<Text>{"String = " + string}</Text>
<Text>{"DecodeS = " + decode}</Text>
</View>
);
};
export default Decode;
The output is
Decode Example
String = asdĞ
DecodeS = asdĞ
In the code above you can also use the standard atob
/btoa
instead of base.decode
/base.encode