Home  >  Article  >  Web Front-end  >  js code example to get the number of bytes of the submitted string

js code example to get the number of bytes of the submitted string

怪我咯
怪我咯Original
2017-07-07 10:39:25994browse

js code for calculating the number of bytes in string

Method 1:

The code is as follows:

function getBytesCount(str) 
{ 
var bytesCount = 0; 
if (str != null) 
{ 
for (var i = 0; i < str.length; i++) 
{ 
var c = str.charAt(i); 
if (/^[\u0000-\u00ff]$/.test(c)) 
{ 
bytesCount += 1; 
} 
else 
{ 
bytesCount += 2; 
} 
} 
} 
return bytesCount; 
}

Method 2:

The code is as follows:

function getBytesCount2(str) 
{ 
if (str == null) 
{ 
return 0; 
} 
else 
{ 
return (str.length + str.replace(/[\u0000-\u00ff]/g, "").length); 
} 
}

The above is the detailed content of js code example to get the number of bytes of the submitted string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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