JKshort
JKshort

Reputation: 143

How to replace multiple characters in string?

I am trying to replace multiple characters in a single string but C character won't change to G, the rest works just fine.

String.prototype.allReplace = function(obj) {
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
    }
    return retStr;
};

console.log('ACGTGGTCTTAA'.allReplace({'A' : 'U', 'C' : 'G', 'G' : 'C', 'T' : 'A'}));

// console.log is UCCACCACAAUU

Upvotes: 1

Views: 203

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21475

You're doing global replaces within your input string at each step, so after you change every instance of C into a G, you then change every instance of G back into a C: later key/value pairs overwrite the results of earlier ones.

Instead, iterate through each character of your input individually:

String.prototype.allReplace = function(obj) {
  var input = this;
  var output = "";
  for (var i = 0; i < input.length; i++) {
    output = output + obj[input.charAt(i)];
  }
  return output;
}
console.log('ACGTGGTCTTAA'.allReplace({
  'A': 'U',
  'C': 'G',
  'G': 'C',
  'T': 'A'
}));

Upvotes: 3

Related Questions