Code Interview – Coderbyte – Swap II – Code challenge – JavaScript Solution Source Code

Coderbyte

Swap II

Have the function SwapII(str) take the str parameter and swap the case of each character. Then, if a letter is between two numbers (without separation), switch the places of the two numbers. For example: if str is “6Hello4 -8World, 7 yes3” the output should be 4hELLO6 -8wORLD, 7 YES3.

function SwapII(str) { 

// Swap the case of each character
  str = str.replace(/([a-z])|([A-Z])/g, function(match, p1, p2) {
    if (p1) {
      return p1.toUpperCase();
    } else {
      return p2.toLowerCase();
    }
  });

  // Look for numbers that are next to letters
  str = str.replace(/\d+[a-zA-Z]+\d+/g, function(match) {
    // Swap the positions of the two numbers
    var firstNum = match.match(/\d+/)[0];
    var secondNum = match.match(/\d+$/)[0];
    var letters = match.match(/[a-zA-Z]+/)[0];
    return secondNum + letters + firstNum;
  });

return str;

}
   
// keep this function call here 
console.log(SwapII(readline()));

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *