Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

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

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?