美文网首页
获取中文转化为英文后字符串长度

获取中文转化为英文后字符串长度

作者: 海豚先生的博客 | 来源:发表于2022-10-10 20:12 被阅读0次
getLength = function(str) {
    // 先把中文替换成两个字节的英文,再计算长度
    return str.replace(/[\u0391-\uFFE5]/g,"aa").length;
}
var length = str.length;
var blen = 0;
for (i=0; i<length; i++) {
  // Unicode编码,Unicode的前128个字符编码和ASCII是一致的,即向后兼容ASCII
  if ((str.charCodeAt(i) & 0xff00) != 0) {
    blen ++;
  }
  blen ++;
}
getLength = function(str) {
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) 
              realLength += 1;
        else
              realLength += 2;
    }
    return realLength;
};

相关文章

网友评论

      本文标题:获取中文转化为英文后字符串长度

      本文链接:https://www.haomeiwen.com/subject/isjzartx.html