I need to try to estimate the DISK size of a text string (which could be raw text or a Base64 encoded string for an image/audio/etc) in JavaScript. I'm not sure how to estimate this. The only thing when Googling i can find is .length
so i thought maybe someone on StackOverflow might know...
The reason i need to know is i have a localStorage script that needs (or would love to have) the ability to check when a user is nearing his 5MB (or 10MB in IE) quota and prompt them to increase the max size for the domain. So, if a user hits, lets say, 4.5MBs of data it'd prompt with
You're nearing your browsers 5MB data cap. Please increase your max data by... [instructions on increasing it for the browser]
It's not going to be exact, but you can count the number of bytes in a string to get a rough estimation.
function bytes(string) {
var escaped_string = encodeURI(string);
if (escaped_string.indexOf("%") != -1) {
var count = escaped_string.split("%").length - 1;
count = count == 0 ? 1 : count;
count = count + (escaped_string.length - (count * 3));
}
else {
count = escaped_string.length;
}
return count;
}
var mystring = 'tâ';
alert(bytes(mystring));