Search code examples
javascriptreplacereplaceall

Convert string letters to different ones in JS


I have this simple JS task that i can't figure out, not so simple for me after all.

Create a function 'converter', that converts letters in this way:

T -> C
C -> T
A -> D
X -> Y

Function accepts String with letters. All non convertable letters should be removed from string.

Example:

 - converter('TTCCAAXX') -> 'CCTTDDYY'
 - converter('TTGG') -> 'CC'

I tried something like this -

function Converter(str) {
let upperStr = str.toUpperCase()
let newStr = upperStr.replaceAll("T", "C").replaceAll("C", "T")
console.log(newStr)
}

Converter("TTCCAAXX")

But this is replacing all the characters and overwriting them and I'm not getting the right results.


Solution

  • You need to use a sequential for loop which is more efficient (only requires one iteration) and solves the overwriting issue.

    For better flexibility we can store the character pairs in an object.

    const convertKeyValue = {
      'T': 'C',
      'C': 'T',
      'A': 'D',
      'X': 'Y'
    }
    
    function Converter(str) {
      let upperStr = str.toUpperCase()
      var newStr = ''
      for(let i = 0; i < upperStr.length; i++){
        const current = upperStr.charAt(i);
        newStr += convertKeyValue[current] ? convertKeyValue[current] : '';
      }
      return newStr;
    }
    
    console.log(Converter('TTCCAAXX'));
    console.log(Converter('TTGG'));