Converting ISBN-10 to ISBN-13
2014-03-12
Introduction
An ISBN (International Standard Book Number) can come in the form of 10 or 13 digits. Old 9-digit SBNs can be converted to 10-digit ISBNs by simply prepending a '0'. Converting from ISBN-10 to ISBN-13, however, is a little more complicated.
This article explains how to convert a 10-digit ISBN to a 13-digit ISBN.
Overview
Converting from ISBN-10 to ISBN-13 involves two steps:
- Prepend the ISBN-10 with the characters "978".
- Remove the ISBN-10 check digit and calculate a new ISBN-13 check digit.
The check digit is the last digit in the ISBN and is used only for verification purposes.
For example:
0-689-85666-0 becomes 978-0-689-85666-2
JavaScript Implementation
First, we convert the ISBN-10 string to an array of characters:
var chars = str.split("");
Then we add "978" to the beginning of the array:
chars.unshift("9", "7", "8");
Remove the ISBN-10 check digit:
chars.pop();
And calculate the ISBN-13 check digit:
var i = 0; var sum = 0; for (i = 0; i < 12; i += 1) { sum += chars[i] * ((i % 2) ? 3 : 1); } var check_digit = (10 - (sum % 10)) % 10; chars.push(check_digit);
Finally, convert the character array back to a string:
var isbn13 = chars.join("");
Putting it All Together
Putting all this into a JavaScript function:
function convertISBN10(isbn10) { var chars = isbn10.split(""); chars.unshift("9", "7", "8"); chars.pop(); var i = 0; var sum = 0; for (i = 0; i < 12; i += 1) { sum += chars[i] * ((i % 2) ? 3 : 1); } var check_digit = (10 - (sum % 10)) % 10; chars.push(check_digit); var isbn13 = chars.join(""); return isbn13; }
It is important to recognize that this function expects a valid ISBN-10 with no additional characters such as spaces or dashes. If the ISBN-10 string is likely to contain additional characters, these should first be removed:
// Convert lowercase 'x' to uppercase 'X' isbn10 = isbn10.replace(/x/g, 'X'); // Remove characters other than 0-9 or X isbn10 = isbn10.replace(/[^0-9X]/g, ''); var isbn13 = convertISBN10(isbn10);
Demo
The following JavaScript demo converts an ISBN-10 to ISBN-13: