LoginSignup
38

More than 1 year has passed since last update.

JavaScript文字列のバイト数を数える - encodeURIComponent版

Last updated at Posted at 2012-11-07

http://qiita.com/items/a46a70b724e3dd9378f2 JavaScript文字列のバイト数を数える - にインスパイアされました。

この記事はブラウザでも使えるコアJavaScriptの範囲でどうするか考えます。Node.js などが持っているバイナリ処理の便利機能等は使わないものとします。

こちらは実際にencodeURIComponent()でUTF-8のバイト列の16進数バイト表記に直して正規表現で処理する形式。バイト数をcharCodeAt()で数えるよりコストはかかるけど、たぶん正確性や保守性は高いんじゃないかな。速度を気にしない場合にどうぞ。

bytes2.js
String.prototype.bytes2 = function () {
    return(encodeURIComponent(this).replace(/%../g,"x").length);
}

コアのprototypeを拡張すると速度が低下することを気にする人用の関数バージョン。

bytes2func.js
function bytes2(str) {
    return(encodeURIComponent(str).replace(/%../g,"x").length);
}

結果

output.js
console.log( "あああa".bytes2() ); // -> 10
console.log( "èî".bytes2() ); // -> 4

試していないけど、UTF-8には6バイトまで種類があるらしいから、これで定義しておけばしばらくは困らないんじゃないかな。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38