LoginSignup
0
0
個人開発エンジニア応援 - 個人開発の成果や知見を共有しよう!-

【GAS】ISBNコード10桁・13桁の相互変換

Last updated at Posted at 2023-10-03

書籍を一意に識別するIBSNコードの桁数を変換するGAS(Google App Script)サンプルコードです。

はじめに

  • 書籍を一意に識別するISBNコードですが、以下のように10桁と13桁の2種類があります。
  • 自分はメルカリによく書籍を出品しているのですが、ISBNコードの10桁と13桁で検索エンジンを検索&出品情報を作成しており、その過程でISBNコードの10桁/13桁を相互変換する機会が多かったので桁数を変換するスクリプトを作成しました。

サンプルコード1(ISBNコード10桁を13桁に変換)

/**
 * ISBN-10からISBN-13に変換
 */
function isbn10to13(isbn10) {

  // ISBNが数値型だったら文字列に寄せる
  isbn10 = (typeof isbn10 == "number") ? isbn10.toString() : isbn10;

  // 桁数が異なる場合は何もしない
  if (isbn10.length != 10) {
    return isbn10;
  }

  // 先頭に978をつけて末尾のチェックディジットを外す
  let isbn13 = "978".concat(isbn10.substring(0, 9));

  let digit = 0;

  for (let i = 0; i < isbn13.length; i++) {

    let no = isbn13.substring(i, i + 1);

    if (((i + 1) % 2) == 0) {
      digit += (no * 3);
    } else {
      digit += (no * 1);
    }
  }

  digit = digit % 10;
  digit = 10 - digit;

  isbn13 = isbn13.concat((digit == 10) ? 0 : digit);

  return isbn13;
}

サンプルコード2(ISBNコード13桁を10桁に変換)

/**
 * ISBN-13からISBN-10に変換
 */
function isbn13to10(isbn13) {

  // ISBNが数値型だったら文字列に寄せる
  isbn13 = (typeof isbn13 == "number") ? isbn13.toString() : isbn13;

  // 桁数が異なる場合は何もしない
  if (isbn13.length != 13) {
    return isbn13;
  }

  // 先頭の978と末尾の1桁チェックディジットを外す
  let isbn10 = isbn13.substring(3, 12);

  let digit = 0;

  for (let i = 0, j = 10; i < isbn10.length; i++, j--) {

    let no = isbn10.substring(i, i + 1);

    digit += no * j;
  }

  digit = digit % 11;
  digit = 11 - digit;

  switch (digit) {
    case 10:
      digit = "X";
      break;
    case 11:
      digit = "0";
      break;
    default:
      digit = digit;
  }

  isbn10 = isbn10.concat(digit);

  return isbn10;
}
0
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
0
0