zoukankan      html  css  js  c++  java
  • JS获取字符串实际长度

    经常要用到的字符串长度检测方法,由于JS原先的长度中文跟英文一样一个字符为1个长度。所以这里就得需要大家自己判断并获取字符串的实际长度了。
        核心代码:
     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) realLength += 1;
     9         else realLength += 2;
    10     }
    11     return realLength;
    12 };

        执行代码:
    alert(jmz.GetLength('测试测试ceshiceshi));
        效果截图:
  • 相关阅读:
    Add Two Numbers
    Reverse Linked List II
    Reverse Linked List
    Remove Duplicates from Sorted List
    Remove Duplicates from Sorted List II
    Partition List
    Intersection of Two Linked Lists
    4Sum
    3Sum
    2Sum
  • 原文地址:https://www.cnblogs.com/zimin1985/p/3360287.html
Copyright © 2011-2022 走看看