Q:

Replace more than one thing in a string

I'm trying to make some kind of secret code language for kids with an online translator.
However, I stumbled upon a problem. I replace the letters of the word from A to Z. But if I have a word like "hi" and I replace the letter 'h' with an 'i', the code will see "ii" when it arrives at the 'h'. Naturally, it will replace both i's with the connected letter. Is there a way I can stop this from happening?
Code example:
var tekst, tevertalen;

tevertalen = prompt("Geef je boodschap in: ",'Default');

...
tekst = tekst.replace("P","S");
tekst = tekst.replace("Q","T");
tekst = tekst.replace("R","A");
...

Thanks in advance!

A:

Iterate over the string character-by-character and use a lookup table:
var mapping = {
    'P': 'S',
    'Q': 'T',
    'R': 'A',
    ...
};

var encoded = '';
var plaintext = 'HI';

for (var i = 0; i < plaintext.length; i++) {
    encoded += mapping[plaintext.charAt(i)];
}

