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!