zoukankan      html  css  js  c++  java
  • js获取字符长度

    方法一:

    var jmz = {};
    jmz.GetLength = function(str) {
      ///<summary>获得字符串实际长度,中文2,英文1</summary>
      ///<param name="str">要获得长度的字符串</param>
      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;
    };
     
    alert(jmz.GetLength('测试测试ceshiceshi));

    方法二(更简洁的方法):

    var l = str.length;
    var blen = 0;
    for(i=0; i<l; i++) {
    if ((str.charCodeAt(i) & 0xff00) != 0) {
    blen ++;
    }
    blen ++;
    }
    方法三(更更简洁的方法):
    var jmz = {};
    jmz.GetLength = function(str) {
      return str.replace(/[u0391-uFFE5]/g,"aa").length;  //先把中文替换成两个字节的英文,在计算长度
    }; 
    alert(jmz.GetLength('测试测试ceshiceshi'));
  • 相关阅读:
    vue中height设置为100%却无法铺满整个页面
    cpp快速上手
    CSP_2020061_线性分类器
    cpp快速上手
    算法笔记
    cpp中set的使用
    cpp中vector的使用
    常用命令
    常用git命令
    Linux使用docker安装fastfs
  • 原文地址:https://www.cnblogs.com/zero7room/p/6689574.html
Copyright © 2011-2022 走看看