JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<table>
<tr><th>Key</th><td><input name="key" length="2" value="M21"/></td></tr>
<tr><th>Message</th><td><input name="message" length="50" value="hello"/></td></tr>
</table>
<button id="submit">
Encode
</button>
<div>
Message in secret code:
</div>
<div id="output">
</div>
JavaScript
function encode(str, key) {
const plainTextLookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const keyLetter = key[0].toUpperCase()
const keyNum = Number(key.slice(1))
const ofs = keyNum - 4 - plainTextLookup.indexOf(keyLetter)
// explanation: code A4, B5 etc. is neutral/no-op
const cryptLookup = plainTextLookup.slice(ofs) + plainTextLookup.slice(0, ofs)
return [... str.toUpperCase()].map(ch => {
const idx = plainTextLookup.indexOf(ch)
if (idx == -1) return ch; else return cryptLookup[idx]
}).join('')
}
$("button#submit").click(function() {
const coded = encode($("input[name='message']").val(), $("input[name='key']").val())
$("#output").text(coded);
})