Home > Web Front-end > JS Tutorial > body text

js method to calculate string length

怪我咯
Release: 2017-06-27 11:38:45
Original
6054 people have browsed it

The following editor will bring you a simple method of getting the actual length of a string (including Chinese characters) using JS. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Method one:

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(&#39;测试测试ceshiceshi));
Copy after login

Method two (more concise method) :

var l = str.length;
var blen = 0;
for(i=0; i<l; i++) {
if ((str.charCodeAt(i) & 0xff00) != 0) {
blen ++;
}
blen ++;
}
Copy after login

Method three (more concise method):

var jmz = {};
jmz.GetLength = function(str) {
  return str.replace(/[\u0391-\uFFE5]/g,"aa").length;  //先把中文替换成两个字节的英文,在计算长度
};  
alert(jmz.GetLength(&#39;测试测试ceshiceshi&#39;));
Copy after login

The above is the detailed content of js method to calculate string length. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template