1

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
0

1 Answer 1

3

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'
}));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.