How can I convert a string to a base64 encoded string in JavaScript?
Rashid D
rashid d profile pic

In JavaScript, you can convert a string to a Base64 encoded string using the built-inbtoa() function. Here's how you can do it:

1
2
3

const stringToEncode = 'Hello, World!';
const encodedString = btoa(stringToEncode);

In this example, thestringToEncode variable holds the string you want to encode, which is'Hello, World!'. Thebtoa() function takes the string as input and returns a Base64 encoded string in theencodedString variable. It's important to note that thebtoa() function works only with ASCII strings. If your string contains non-ASCII characters or Unicode characters, you need to convert them to a compatible format before encoding. One common approach is to use theencodeURIComponent() function to ensure proper encoding:

1
2
3

const stringToEncode = 'Привет, Мир!';
const encodedString = btoa(encodeURIComponent(stringToEncode));

In this example, theencodeURIComponent() function is used to convert the string to a URI-encoded format before passing it tobtoa() for encoding. Please note that thebtoa() function encodes the string using the Base64 encoding algorithm. However, the encoded string may not be suitable for all contexts. Some environments or protocols may require additional processing or different encoding schemes for proper handling of data. To decode a Base64 encoded string back to its original form, you can use theatob() function:

1
2

const decodedString = atob(encodedString);

In this example,atob() decodes theencodedString back to its original form, and the result is stored in thedecodedString variable. Always consider the compatibility and security implications when working with Base64 encoded strings, as they may have size limitations and are not suitable for all types of data.