Home > Web Front-end > JS Tutorial > 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

怪我咯
Release: 2017-07-07 10:39:25
Original
1037 people have browsed it

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; 
}
Copy after login

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); 
} 
}
Copy after login

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!

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