LoginSignup
1
0

More than 3 years have passed since last update.

原稿用紙枚数換算

Posted at

文字列を原稿用紙枚数換算する処理が必要になったからついでにまとめとく。

原稿用紙枚数を換算する関数

JavaScript
const manuscriptCount = (text) => {
  let lines = 0;

  const textArray = text.split("\n");

  textArray.forEach(t => {
    if (t.length === 0) {
      lines += 1;
    } else {
      t = t.slice(0,1) === (" " || "") ? t : " " + t;
      t = t.replace("。」","").replace(/(\d{2})/g, "0").replace(/[a-zA-Z]{2}/g, "a");

      let start = 0;
      let end = start + 21;
      while (start < t.length) {
        lines++;
        start = t.slice(-1) === ("" || "" || "") ? end : end - 1;
        end = start + 21;
      }
    }
  });

  return ((lines / 20) | 0) + 1;
};

const text = "処理する文字列";

console.log(manuscriptCount(text));

処理について

  • 改行コードで分割して配列にする(改行コードのぶれは今回は無視)
  • 分割した配列について以下の処理
    • 改行のみで文字数0だったら1行増やす
    • 文字数0でなければ以下の処理
      • 一文字目がスペースまたは鍵括弧(「)ではなかったらスペースを追加
      • 句点+鍵括弧(。」)は1文字、半角英数字は2桁で1文字分にしてカウント
      • 20文字ごとに行数のカウントを増やす(21文字取得して行末の文字を判別する)
      • 行頭の記号(」、。)はぶら下げ処理をするから無視、それ以外の場合は次の開始位置を1文字戻す
  • 20行につき原稿用紙1枚で出力

行頭に小書き文字が来るのは原稿用紙のルール的にはありらしいから処理してない。
考慮すべき要素は網羅してるはず。
文章書きではないから正確性の保証はできないけど、おおよその枚数把握にはなる。

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