Home >Web Front-end >JS Tutorial >js gets the number of bytes of the submitted string_javascript skills

js gets the number of bytes of the submitted string_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:56:02890browse

Method 1:

Copy code 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:
Copy code The code is as follows:

function getBytesCount2(str)
{
if (str == null)
{
return 0;
}
else
{
return (str.length str.replace(/[u0000-u00ff]/g, "").length);
}
}
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