LoginSignup
7
7

More than 5 years have passed since last update.

JavaScriptで全角を2、半角を1で数える(半角カタカナ対応)

Last updated at Posted at 2017-12-19

同種のものはたくさんあるのですが、半角カタカナを2と数えるものが多かったため
1と数えるよう変更したものです。

var charcount = function (str) {
    len = 0;
    str = str.split("");
    for (i=0;i<str.length;i++) {
        if (str[i].match(/[ア-ン゙゚]+/)){
            // 半角カタカナ
            len++;
        } else {
            esc = escape(str[i]);
            if (esc.match(/^\%u/)){
                // 全角
                len+=2;
            } else {
                // 半角英数
                len++;
            }
        }
    }

    return len;
}
7
7
1

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