var calculateNUSMatricNumber = function (id) {
var matches = id.toUpperCase().match(/^A\d{7}|U\d{6,7}/);
if (matches) {
var match = matches[0];
// Discard 3rd digit from U-prefixed NUSNET ID
if (match[0] === 'U' && match.length === 8) {
match = match.slice(0, 3) + match.slice(4);
}
var weights = {
U: [0, 1, 3, 1, 2, 7],
A: [1, 1, 1, 1, 1, 1]
}[match[0]];
for (var i = 0, sum = 0, digits = match.slice(-6); i < 6; i++) {
sum += weights[i] * digits[i];
}
return match + 'YXWURNMLJHEAB'[sum % 13];
}
};
$('input').on('change keyup', function () {
$('span').text(calculateNUSMatricNumber(this.value) || 'Invalid input!');
});
External resources loaded into this fiddle:
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">NUS Matriculation Number Calculator</div>
<div class="panel-body">
<div class="input-group input-group-lg">
<input type="text" class="form-control" placeholder="A0012345 / A0012345A / a0012345 / [email protected]">
<span class="input-group-addon">Output</span>
</div>
</div>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Input Format</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Matriculation number with missing check digit</td>
<td>A0012345</td>
</tr>
<tr>
<td>Matriculation number with wrong check digit</td>
<td>A0012345A</td>
</tr>
<tr>
<td>NUSNET ID</td>
<td>a0012345</td>
</tr>
<tr>
<td>NUS email address</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
</div>
</div>
.container {
padding-top: 15px;
}