2

I want to replace multiple characters in a string using regex. I am trying to swap letters A and T as well as G and C.

function replacer(string) {
    return "String " + string + " is " + string.replace(/A|T|G|C/g, "A","T","G","C");
}

do I have the regex expression correct?

thanks

IlGala
  • 3,331
  • 4
  • 35
  • 49
MaxES
  • 81
  • 1
  • 7

3 Answers3

4

I suggest combining the replace callback whose first argument is the matching character with a map from character -> replacement as follows:

// Swap A-T and G-C:
function replacer(string) {
  const replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'};
  return string.replace(/A|T|G|C/g, char => replacements[char]);
}

// Example:
let string = 'ATGCCTCG';
console.log('String ' + string + ' is ' + replacer(string));
le_m
  • 19,302
  • 9
  • 64
  • 74
2

You could do it this way too:

function replacer(string) {
    var newString = string.replace(/([ATGC])/g, m =>
    {
     switch (m) {
          case 'A': return 'T';
          case 'T': return 'A';
          case 'G': return 'C';
          case 'C': return 'G';
      }
    });
    return "String " + string + " is " + newString;
}

console.log(replacer('GATTACAhurhur'));
1

A, T, G, C - Looks like you are referring to DNA base pairs :)

Aim is to swap A with T and G with C. Assuming the input string never contains the character Z, a simple swap function using regex:

Note: Change Z with another character or symbol that you are confident will not appear in the input string. Example $ maybe?

var input = "AAATTGGCCTAGC"
input = input.replace(/A/g,"Z").replace(/T/g,"A").replace(/Z/g,"T");
input = input.replace(/G/g,"Z").replace(/C/g,"G").replace(/Z/g,"C");
console.log(input);
degant
  • 4,861
  • 1
  • 17
  • 29