3
2

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.

javascriptでJAN(EAN)のチェックデジット

Posted at

javascriptでバーコードのチェックデジットの整合性を見るスクリプト。
計算があっていればtrueを返す。

参考
http://www.dsri.jp/jan/check_digit.html
https://qiita.com/cress_cc/items/3e820fe1695f13793df3

code
    function eanCheckDigit(barcodeStr) { // 引数は文字列
        // 短縮用処理
        barcodeStr = ('00000' + barcodeStr).slice(-13);
        let evenNum = 0, oddNum = 0;
        for (var i = 0; i < barcodeStr.length - 1; i++) {
            if (i % 2 == 0) { // 「奇数」かどうか(0から始まるため、iの偶数と奇数が逆)
                oddNum += parseInt(barcodeStr[i]);
            } else {
                evenNum += parseInt(barcodeStr[i]);
            }
        }
        // 結果
        return 10 - parseInt((evenNum * 3 + oddNum).toString().slice(-1)) === parseInt(barcodeStr.slice(-1));
    }

    // example
    // 通常13桁
    if (eanCheckDigit("4569951116179")) console.log("true"); // true
    // 短縮版
    if (eanCheckDigit("49968712")) console.log("true"); // true
3
2
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?