VBScript と Javascript の表示文字列用バイト計算

  VBScript のバイト計算



VBScript では たいていにおいて SHIFT_JIS が前提なので、日本語の扱いとして「全角/半角」を判断したい場合があります。その場合は以下のコードを利用する事ができます

REM **********************************************************
REM 文字列のバイト計算
REM **********************************************************
Function ByteLen( strTarget )

	Dim i,nLen,nRet,strMoji,nAsc

	nRet = 0

	nLen = Len( strTarget )

	For i = 1 to nLen
		nRet = nRet + 2
		strMoji = Mid( strTarget, i, 1 )
		nAsc = Asc( strMoji )
		if &H0 <= nAsc and nAsc <= &H80 then
			nRet = nRet - 1
		end if
		if &HA0 <= nAsc and nAsc <= &HDF then
			nRet = nRet - 1
		end if
		if &HFD <= nAsc and nAsc <= &HFF then
			nRet = nRet - 1
		end if
	Next

	ByteLen = nRet

End Function


&H0 から &H1F までは、表示目的には必要ありませんが、他の目的では必要な場合がありますコードの判断基準は、IsDBCSLeadByte 関数 という関数でテストした結果を元にしています






  JavaScript のバイト計算



JavaScript は必ずしも SHIFT_JIS を前提にしていません。と言うよりは、Unicode を内部コードとした処理が通常メソッドとして提供されています。



alert("\\".charCodeAt(0).toString(16))
alert(String.fromCharCode(parseInt("5C",16)))
alert("~".charCodeAt(0).toString(16))
alert(String.fromCharCode(parseInt("7E",16)))

str = ""
for( i = 0x20; i &lt;= 0x7e; i++ ) {
	str += String.fromCharCode(i);
}
alert(str);

str = ""
for( i = 0xff61; i &lt;= 0xff9f; i++ ) {
	str += String.fromCharCode(i);
}
alert(str);


このテストを実行するにあたって、Unicode対応 文字コード表 を参考にしました。
コードの範囲で表示文字列としての「半角」が判断できるので以下のようなメソッドをString オブジェクトに追加実装する事ができます。

String.prototype.byteLen = function() {

	var str = this.toString();
	var len = str.length;
	var i,cd,blen=0;

	for( i = 0; i &lt; len; i++ ) {
		blen += 2;
		cd = str.charCodeAt(i);
		if ( 0x20 &lt;= cd &amp;&amp; cd &lt;= 0x7e ) {
			blen--;
		}
		if ( 0xff61 &lt;= cd &amp;&amp; cd &lt;= 0xff9f ) {
			blen--;
		}
	}

	return blen;
}

alert("日本語OK".byteLen())















  infoboard   管理者用   
このエントリーをはてなブックマークに追加





フリーフォントWEBサービス
SQLの窓WEBサービス

SQLの窓フリーソフト

素材

一般WEBツールリンク

SQLの窓

フリーソフト

JSライブラリ