-2

I need to convert all the G's into C's and C's to G's. Can someone help me find a way to stop the G and C from contradicting themselves? What I have so far:(I am beginner level at coding)

var str = "ATGC";
var step1 = (str.replace (/A/g, 'U'));
var step2 = (step1.replace (/T/g, 'A'));
var step3 = (step2.replace (/C/g, 'G'));
var step4 = (step3.replace (/G/g, 'C'));
var convertedStr = step4;
console.log(convertedStr);

End result is UACC because the step3 changes the C's to a G and then step4 changes both new G's into C's

Barmar
  • 741,623
  • 53
  • 500
  • 612
AddisonL
  • 7
  • 1
  • Change the Cs to $s first, then the Gs to Cs, then the $s to Gs. Another way is to turn the string into an array of characters and use Array.map() to replace the characters. (also, the point of this exercise is probably to figure this out on your own ;) –  Feb 23 '22 at 21:54
  • Interview question? – JoeKincognito Feb 23 '22 at 21:57

1 Answers1

3

Do it all at once with a single call that uses a function to calculate the replacement.

var str = "ATGC";
const pairs = {
  A: 'U',
  T: 'A',
  C: 'G',
  G: 'C'
};

var convertedStr = str.replace(/[ATCG]/g, c => pairs[c]);
console.log(convertedStr);
Barmar
  • 741,623
  • 53
  • 500
  • 612