当前位置: 首页 > Web前端 > JavaScript

JavaScript计算字符串的实际长度

时间:2023-03-27 17:05:07 JavaScript

计算字符串的实际长度,双字节字符(包括汉字)长度计为2,ASCII字符长度计为1方法一:使用match:exportfunctiongetByteLenMatch(data){letresult=0;for(letsofdata){result+=s.match(/[^\\x00-\\xff]/ig)==null?1:2;}returnresult;}方法二:使用replace:exportfunctiongetByteLenReplace(data){returndata.replace(/[^\\x00-\\xff]/ig,"aa").length;}测试代码:让testData=newArray(50000000).fill("ha").toString();for(leti=0;i<3;i++){console.time("getByteLenMatch");getByteLenMatch(测试数据);console.timeEnd("getByteLenMatch");console.time("getByteLenReplace");getByteLenReplace(测试数据);.timeEnd("getByteLenReplace");}性能比较(单位ms):字符串长度matchreplace50,000,0008051862650,000,0009351801950,000,00010384751210,000,0001631178310,000,0001646134310,000,000166313725,000,0007997285,000,0008228065,000,0008846451,000,0001651281,000,0001661431,000,000170113500,0008458500,0008354500,0008661100,000207100,000185100,00020550,00011.793.0150,00010.392.6850,00011.992.8210,0004.130.6010,0004.320.5910,0005.480.585,0001.880.315,0001.360.335,0002.710.311,0001.670.071,0000.210.071,0001.020.065000.08400.03225000.08200.03325000.08400.03201000.02290.01001000.04320.01491000.04710.0161在大数据量情况下,replace性能初次会劣于match,多次执行后会优于match,小数据量Inthecase,replaceperformanceisbetterthanmatch