3👍
✅
It’s not saying that arr[0]
might be null, it’s saying that .match(/:(.*?);/)
might return null. So to check for this would be:
const match = arr[0].match(/:(.*?);/);
if (match) {
const mime = match[1];
// ... the rest of the code
}
0👍
you can change
from arr[0].match(/:(.*?);/)[1];
to arr[0].match(/:(.*?);/)?[1];
it is coming from second index, not the first one.
0👍
I could rewrite it this way
dataURLtoBlob(dataurl: string): Blob {
const arr: string[] = dataurl.split(',');
// fail fast
if(!Array.isArray(arr) || !arr[0] || !arr[1])
return new Blob();
// can change this to const if you are not planning to set a default mimetype
let mime = arr[0].match(/:(.*?);/)[1];
// or you can force typescript compiler to consider this as (string or whatever is the type) with type casting as follow
// const mime = <string>arr[0].match(/:(.*?);/)[1];
// const mime = arr[0].match(/:(.*?);/)[1] as string; whatever you like
if(!mime)
// mime = 'default mime' in case you have a default mime type
// or return new Blob() or anything you plan to do in case mime type does not exist
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
This way you don’t end up with deep level nested blocks which usually is hard to read.
Source:stackexchange.com