5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2012-11-07

JavaScriptのString#lengthは文字数を返すためバイト数を出すメソッドを追加する。
たとえばDBにバイト数で制限がかかっていてフロントでも補助的にバリデーションをかけるような場合に。

bytes.js

String.prototype.bytes = function () {
    var bytes = 0,
        i,c,
        len = this.length;
    for(i=0 ;i < len ; i++){
        c = this[i].charCodeAt(0)
        if (c <= 127){
            bytes += 1;
        } else if (c <= 2047){
            bytes += 2;
        } else {
            bytes += 3;
        }
    }
    return bytes;
};

下記のようになる

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

ただし、この実装は厳密ではない

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?