简体   繁体   中英

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" ?

You have to assign each changes. It's working now

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());
      after = x; 
      //console.log("inside"+x);
    }
  }

  console.log(x);
}

switchItUp("HiYouThere", "biyouthere");

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);
}

This is code:

 function switchItUp(before, after) { for (var i = 0; i < before.length; i++) { if (before.charAt(i) == before.charAt(i).toUpperCase()) { after = after.replace(after.charAt(i), after.charAt(i).toUpperCase()); } } return after; } var after = switchItUp("HiYouThere", "biyouthere"); document.body.innerHTML+='<p style="color: black;">'+ after + '<p/>'; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM