Search code examples
javascriptreplacecharat

replacing multiple letter in a string javascript


Hi I am looking to compare two strings and have all the lowercase letters in string B -which are uppercase letters in string A- to uppercase, the problem with my code is it only changes the last letter like this

var i;
var x;

function switchItUp(before, after) {
  for (i = 0; i < before.length; i++) {
    if (before.charAt(i) == before.charAt(i).toUpperCase()) {
      x = after.replace(after.charAt(i), after.charAt(i).toUpperCase());

    }
  }

  console.log(x);
}




switchItUp("HiYouThere", "biyouthere");

this will result in "biyouThere" any way to change it to "HiYouThere" ?


Solution

  • I have modified your code correctly to work. You needed to apply the operation to the same variable, x, not after, in every loop.

    function switchItUp(before, after) {
      var x = after;
      for (i = 0; i < before.length; i++) {
        if (before.charAt(i) == before.charAt(i).toUpperCase()) {
          x = x.replace(after.charAt(i), after.charAt(i).toUpperCase());
    
        }
      }
    
      console.log(x);
    }