[js] 使用js写一个计算字符串的字节数的方法

haizhilin2013
2020-01-21 03:37:39 星期二
js
                    
                        
使用js写一个计算字符串的字节数的方法
Comments per page
< Page 1 / 1 >
bigbanana 2020-06-04 02:30:49

'中文a【】,'.split('').reduce((len, it) => len+=it.charCodeAt(0).toString(16).length/2, 0)

NAZBIN 2020-06-08 12:40:53

const computeLens = (s) => {
return s.split('').length
}

console.log(computeLens('aaacvsa'));

wind8866 2022-03-23 08:34:09

是字节数而不是字符数

const strByteLength = (str) => {
  return (new TextEncoder()).encode(str).byteLength
}
strByteLength('c')// 1
strByteLength('你')// 3
strByteLength('𠮷')// 4
strByteLength('👏🏿')// 8
strByteLength('👩‍👩‍👧‍👧')// 25
xiaoqiangz 2022-08-31 05:59:47

String.prototype.byteLength = function() {
var count = 0;
for(let i=0; i< this.length; i++) {
count +=this.charCodeAt(i) <= 128 ? 1 : 2
}
return count
}

排行榜
今日答题答题排行
    未答的题
    更多>
      【关注作者公众号】 以面试驱动学习--前端剑解
      【公众号推荐】 不折腾的前端和咸鱼有什么区别

      学习不打烊,充电加油只为遇到更好的自己,365天无节假日,每天早上5点纯手工发布前端知识点(死磕自己,愉悦大家)。希望大家在这浮夸的前端圈里,保持冷静,坚持每天花20分钟来学习与思考。在这千变万化,类库层出不穷的前端,建议大家不要等到找工作时,才狂刷题,提倡每日学习!欢迎大家关注3+1开源项目!希望大家每人去学习与思考!(不要为了谁而来,要为自己而努力!

      【关注官方公众号】 每天4:30-5:00推送
      【公众号推荐】 一起折腾前端算法
      【微信学习群】 备注3+1