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 use `XMLHttpRequest` to do the dirty work for you:

```js
var url = document.createElement("canvas").toDataURL(); // some data-uri

var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
  // result = ArrayBuffer, from here assign a view to it
  if (xhr.status === 200) console.log(new Uint8Array(xhr.response));
};
xhr.send();
```

It's a little more code than using `atob()` but all conversion happens internally. It's async too which can help with larger Data-URIs.

In newer browsers (which supports it) you can instead use `fetch()`:

```js
// note: atm not all browsers support these features.
fetch(document.createElement("canvas").toDataURL())  // pass in some data-uri
  .then(function(response) {return response.arrayBuffer()})
  .then(function(buffer) {
    console.log(new Uint8Array(buffer));
  });
```
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.
> 
> 
>