zoukankan      html  css  js  c++  java
  • JS获取字符串实际长度(包含汉字)的简单方法

    方法一:

     1 var jmz = {};
     2 jmz.GetLength = function(str) {
     3   ///<summary>获得字符串实际长度,中文2,英文1</summary>
     4   ///<param name="str">要获得长度的字符串</param>
     5   var realLength = 0, len = str.length, charCode = -1;
     6   for (var i = 0; i < len; i++) {
     7     charCode = str.charCodeAt(i);
     8     if (charCode >= 0 && charCode <= 128) 
     9        realLength += 1;
    10     else
    11        realLength += 2;
    12   }
    13   return realLength;
    14 };
    15  
    16 alert(jmz.GetLength('测试测试ceshiceshi));

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

    1 var l = str.length;
    2 var blen = 0;
    3 for(i=0; i<l; i++) {
    4 if ((str.charCodeAt(i) & 0xff00) != 0) {
    5 blen ++;
    6 }
    7 blen ++;
    8 }

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

    1 var jmz = {};
    2 jmz.GetLength = function(str) {
    3   return str.replace(/[u0391-uFFE5]/g,"aa").length;  //先把中文替换成两个字节的英文,在计算长度
    4 };  
    5 alert(jmz.GetLength('测试测试ceshiceshi'));
  • 相关阅读:
    Python Day23
    Python Day22
    Python Day21
    Python Day20
    Python Day19
    Python Day18
    Python Day17
    Python Day15
    Appium python unittest pageobject如何实现加载多个case
    Appium python Uiautomator2 多进程问题
  • 原文地址:https://www.cnblogs.com/JQstronger/p/GetLength.html
Copyright © 2011-2022 走看看