JavaScriptで文字列のバイト数を求める
countByteは、文字列のバイト数を求める関数です。
<html>
<body>
<script type="text/javascript">
<!--
function countByte(str) {
var count = 0;
for(var i = 0; i < str.length; i++) {
if (escape(str.charAt(i)).length < 4) {
count++;
}
else {
count += 2;
}
}
return count;
}
// -->
</script>
<form name="FM">
<p>
<input type="text" name="IT" size="30">
<input type="text" name="CountByte" size="10" readonly="readonly">
</p>
<p>
<input type="button" value="文字バイト数取得" onclick="document.FM.CountByte.value=countByte(document.FM.IT.value)">
</p>
</form>
</body>
</html>charAtで文字列中の1文字を取り出し、escapeでjavascriptでのURLエンコードを行う。
するとアスキー文字系は1バイト、&!#等は3バイト、漢字は4バイト以上になる。