当前位置:   article > 正文

获取字符串的长度_unicode环境下计算字符串长度

unicode环境下计算字符串长度

获取字符串的长度

题目
如果第二个参数 bUnicode255For1 === true,则所有字符长度为 1
否则如果字符 Unicode 编码 > 255 则长度为 2

解答

function strLength(s, bUnicode255For1) {
    if(bUnicode255For1===true){
        return s.length;
    }else{
        let len = 0;
        for(let i=0; i<s.length;i++){
            if(s.charCodeAt(i)>255){
                len +=2;
            }else{
                len++;
            }
        }
        return len;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
'
运行
charCodeAt()方法

格式:str.charCodeAt(index)

知识点:判断Unicode编码长度、charCodeAt()方法

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/1000051
推荐阅读
相关标签
  

闽ICP备14008679号