Raven
Raven

Reputation: 221

JavaScript Replace every letter with a different set of letters but not redo already replaced pieces

I want to replace every letter in a string with a 3 other letters. At the bottom I have a possible fix, and my real question is if it is good solution.

How my code currently works is that it takes all the letters "a", and replaces them with "aug" then looks at any "b"s and replaces them with "cuu", going on until it reaches "z".

However, the problem occurs as it comes to, say, "g." having replaced an "a" into "aug", the "g" in aug will be replaced expanding it more and getting me a wrong result. I've got a function that looks like:

function e(letter, codon) {
    text = text.replace(letter, codon);
}

Then I run the function for all the letters.

e(/a/g,"gcu");
e(/b/g,"uag");
e(/c/g,"ugu");
//etc..

So for a string:

text = "hello guy";

the desired output of the program would turn it into "caugaacuucuuuga ggguuuuau"

The actual output is "cauuugggaacuuuuuucuuuuuuuuuga ggguuuuau", however. This is because when it reaches "g" in "guy" it replaces the already edited text.

My fix for this would be to make it instead of replacing it with 3 normal letters, it instead would turn each letter into a useless character or long string of characters, of which it will then later turn into the 3 letters I want. My main question is if this is a legitimate solution, or if it is ridiculous?

Please forgive me being new to this, and I hope my question is formatted nicely.

Upvotes: 0

Views: 90

Answers (2)

rkmax
rkmax

Reputation: 18133

I think it's better split first the word and then replace it. e.g.

var text = 'hello guy';
var chars = text.split('');
var result = '';
var replaceTable = {
  'a': 'gcu',
  'b': 'uag',
  'c': 'ugu'
};

for (var i = 0; i < chars.length; i++) {
 var replaced = replaceTable[chars[i]];
 result += replaced ? replaced : chars[i];
}

Assuming you have the full character table you will have the result you want

Upvotes: 2

Pedro Estrada
Pedro Estrada

Reputation: 2404

Using your example of the string

 var text = "hello guy";

and using the solution provided by rkmax of having a replace table.

var replaceTable = {
  'a': 'gcu',
  'b': 'uag',
  'c': 'ugu'
};

Just do a for loop on the string itself:

for (var i=0; i < text.length; i++) {
    e(text[i], replaceTable[text[i]]);
}

Upvotes: 0

Related Questions