Question: I want to convert "base64" string into bytes array through the javascript.

I received string from the URL like.

```
 ("data:image/jpeg;base64,/9j/4QN6RXhpZgAASUkqAAgAAAAIA)

```

And i want to convert the string into bytes array. because i need this byte array to send Rest API endpoint. The rest API Content-type=application/octet-stream.

Answer: 
You can try with the following;

```
function test(base64StringFromURL)
{
   var parts = base64StringFromURL.split(";base64,");
   var contentType = parts[0].replace("data:", "");
   var base64 = parts[1];
   var byteArray = base64ToByteArray(base64);
   ..
}

function base64ToByteArray(base64String) {
        try {            
            var sliceSize = 1024;
            var byteCharacters = atob(base64String);
            var bytesLength = byteCharacters.length;
            var slicesCount = Math.ceil(bytesLength / sliceSize);
            var byteArrays = new Array(slicesCount);

            for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
                var begin = sliceIndex * sliceSize;
                var end = Math.min(begin + sliceSize, bytesLength);

                var bytes = new Array(end - begin);
                for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
                    bytes[i] = byteCharacters[offset].charCodeAt(0);
                }
                byteArrays[sliceIndex] = new Uint8Array(bytes);
            }
            return byteArrays;
        } catch (e) {
            console.log("Couldn't convert to byte array: " + e);
            return undefined;
        }
    }

```
This would prove to be much short solution.

```
const byteArray = new Buffer(base64String.replace(/^[\w\d;:\/]+base64\,/g, ''), 'base64');

```

> 
> base64String is the string containing the base 64 string.
> 
> 
> 

> 
> byteArray is the array you need.
> 
> 
> 

> 
> The regex replacement is optional and is just there to deal with prefix as in the case of dataurl string.
> 
> 
>