LoginSignup
15
12

More than 5 years have passed since last update.

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

Posted at

JavaScript文字列のバイト数を数える - encodeURIComponent版 にインスパイアされました。

HTML5 で追加された Blob オブジェクト を使うことで、マルチバイト文字も正確に高速にバイト数を求めることが出来ます。

prototype 汚染を気にしない人向け

str_size.js
String.prototype.size = function () {
  return (new Blob([this], {type: "text/plain"})).size;
};

生理的に prototype 拡張が無理な人向け

getStrSize.js
function getStrSize(str) {
  return (new Blob([str], {type: "text/plain"})).size;
}

結果

example.js
console.log( "あああa".size() ); // -> 10
console.log( "èî".size() ); // -> 4
console.log( "?野家".size() ); // -> 10

短文では、 Blob インスタンスの生成コストの分 encodeURIComponent版 よりも遅くなりますが、長文では威力を発揮します。

File API をサポートしていない IE9 以前では動かないので、 IE9 が切り捨てられる環境で使いましょう。
Blob の使えるブラウザ

15
12
0

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
15
12