-1

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!

M. Boeckx
  • 252
  • 1
  • 5
  • 18
  • 1
    Duplicate http://stackoverflow.com/questions/10947046/jquery-find-and-replace-multiple-items – Akshay Joy May 25 '13 at 18:26
  • Downvoting for tagging this as "jQuery". People *really* need to learn the difference between jQuery and JavaScript. One's a library, one's a language. Not at all the same. – mpen May 25 '13 at 18:31
  • Thanks, I took a look at these topics and I understand what they do now. I think I'll be using Blender's solution though. – M. Boeckx May 25 '13 at 18:32

1 Answers1

3

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)];
}
Blender
  • 289,723
  • 53
  • 439
  • 496