I am looking for a way to code numbers into letters. I want to take an inputted django variable and flip the numbers to letters using the following:
1=M
2=A
3=k
4=E
etc.
What is the best way to complete this? I have looked at the switch function, but I can only seem to get it to work for 1 character. How would I get it to switch each number outputted from a Django variable?
<script type="text/javascript">
function myFunction() {
var text;
var Number = {{ Label.MetaData.price|number_format(0, '', '')|raw }};
switch(Number) {
case "1": text = "M"; break;
case "2": text = "A"; break;
case "3": text = "K"; break;
case "4": text = "E"; break;
}
document.getElementById("code").innerHTML = text; }
</script>
<p id="code"></p>
Using an object is probably the easiest way. Here's an example.
const letterMap = {
" ": 0,
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 7,
h: 8,
i: 9,
j: 10,
k: 11,
l: 12,
m: 13,
n: 14,
o: 15,
p: 16,
q: 17,
r: 18,
s: 19,
t: 20,
u: 21,
v: 22,
w: 23,
x: 24,
y: 25,
z: 26,
}
const sentence = "the quick brown fox jumped over the lazy dog"
for (const char of sentence) console.log(letterMap[char]);
Edit: Replaced single quotes.
const characterString = 'MAKE';
const myNumber = 2 // replace with yours
const myLetter = characterString.charAt(myNumber); // K
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt