4
6

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.

2バイト文字は2として文字列の長さをカウントするGoogleAppsScript関数

Last updated at Posted at 2017-01-11

文字列の長さをカウントする関数

  • GoogleAppsScriptでの文字カウント

 次のようにしても,lenが7になってしまう。

文字数カウント
  var str="ようこそGAP";
  var len = str.len; //lenは7になる
  • 2バイト文字は2としてカウントする関数
文字数カウント
function main(){
  var str="ようこそGAP";
  var len = strLenJ(str); //lenは11になる
}

function strLenJ(str) {//2バイト文字は2として文字数をカウント
  var len = 0;
  str = escape(str);
  for (var i = 0; i < str.length; i++, len++) {
    if (str.charAt(i) == "%") {
      if (str.charAt(++i) == "u") {
        i += 3;
        len++;
      }
      i++;
    }
  }
  return len;
}

参考:http://www.tohoho-web.com/js/string.htm

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?