const regex = /^(?:ISBN(?:-13)?:? )?(?<gs1>\d{3})(?:(?<number>\d{9})|(?=[\d -]{14}$)[ -](?<registrationGroup>\d{1,5})[ -](?<registrant>\d{1,7})[ -](?<publication>\d{1,6})[ -])(?<checkDigit>\d)$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^(?:ISBN(?:-13)?:? )?(?<gs1>\\d{3})(?:(?<number>\\d{9})|(?=[\\d -]{14}$)[ -](?<registrationGroup>\\d{1,5})[ -](?<registrant>\\d{1,7})[ -](?<publication>\\d{1,6})[ -])(?<checkDigit>\\d)$', 'gm')
const str = `9781861978769
97818619787659
978186197879
978-1-86197-876-9
978-1-86197-87-9
978-1-86197-8765-9
978-186197-876-9
978-186197-8-76-9`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions