我如何估计使用JavaScript字符串的磁盘大小? [英] How can I estimate the disk size of a string with JavaScript?
问题描述
我要尝试估计的磁盘的文本串(可以是原始文本,或者以Base64 EN codeD字符串影像/音频/等)在JavaScript中的大小。我不知道如何估算这一点。谷歌搜索我能找到的时候,唯一的事情是。长度
,所以我想也许有人在计算器上可能知道...
究其原因,我需要知道的是,我有一个需要localStorage的脚本(或很想有),当用户接近他的5MB(或10MB的IE浏览器)来检查配额,促使他们增加最大规模的能力域。所以,如果一个用户点击,可以说,它会与提示数据4.5MBs
您正在接近你的浏览器5MB的数据上限。由... [于增加它的浏览器的说明] 的
请增加你的最大数据
块引用>解决方案这不会是精确的,但你可以指望字符串中的字节数得到一个粗略的估计。
函数字节(字符串){
VAR escaped_string = EN codeURI(字符串);
如果(escaped_string.indexOf(%)!= - 1){
。VAR计数= escaped_string.split(%)长度 - 1;
数=计== 0? 1:计数;
数=计+(escaped_string.length - (计数* 3));
}
其他{
数= escaped_string.length;
}返回计数;
}
VAR了mystring ='助教';
警报(字节(MyString的));
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));
这篇关于我如何估计使用JavaScript字符串的磁盘大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!