I am working with a substitution cipher, where each letter of the alphabet is represented by a letter from the substituted alphabet.
function substitution(input, alphabet) { let str = ''; let result = input.split(''); alphabet = alphabet.split(''); for (let i = 0; i < result.length; i++) { if (alphabet.includes(result[i])) { str += alphabet[i]; console.log(str); } } //console.log(str); return str; } substitution('ab c', 'plmoknijbuhvygctfxrdzeswaq');
The output I’m expecting is 'pl m'
, however I am getting 'plo'
as the space moves to the next letter since there isn’t a space in the substituted alphabet. Is there a way to preserve that space without using regex?
Advertisement
Answer
If the letter is in your alphabet, you add the encrypted letter. But if it’s not in the alphabet, you don’t do anything. You should still add it, just not encrypted:
function substitution(input, alphabet) { let str = ''; let result = input.split(''); alphabet = alphabet.split(''); for (let i = 0; i < result.length; i++) { if (alphabet.includes(result[i])) { str += alphabet[i]; console.log(str); } else { str += result[i]; } } //console.log(str); return str; } substitution('ab c', 'plmoknijbuhvygctfxrdzeswaq');