Categories
JavaScript Answers

How to Get the Extension of an Base64 Image with JavaScript?

Spread the love

Sometimes, we want to get the extension of an base64 image with JavaScript.

In this article, we’ll look at how to get the extension of an base64 image with JavaScript.

Get the Extension of an Base64 Image with JavaScript

To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split.

Then we get the first item from that.

And, then we call split again to split the returned string by the /.

Then we get the file extension by taking the 2nd element from the returned result.

For instance, we write:

const base64Data = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
const [,type] = base64Data.split(';')[0].split('/');
console.log(type)

to split base64Data by the colon with:

base64Data.split(';')[0]

Then we call split to split the returned string with .split('/').

And finally, we take the 2nd item and assign it to type with the destructruing syntax.

Therefore, we should see that type is 'png' from the console log.

Conclusion

To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split.

Then we get the first item from that.

And, then we call split again to split the returned string by the /.

Then we get the file extension by taking the 2nd element from the returned result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Get the Extension of an Base64 Image with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *