Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Transfer all letters in string into uppercase or lowercase

I am a beginner in Javascript.
I tried to make a function about covert string into uppercase or lowercase. But I am confused why it can get expected output. Following is my function purpose and codes.Thank you!

  1. Function purpose :

When letter in string is uppercase, it will change into lowercase. When letter in string is lowercase, it will change into uppercase. For example: "Peter" will transfer into "pETER"

  1. Question:

I can't understand why my code ends up with "Peter" rather then "pETER"

function swap(str) {
  var name = ''
  for (i = 0; i <= str.length - 1; i++) {
    if (str[i] >= 'a' && str[i] <= 'z') {
      str[i].toUpperCase()
    } else {
      str[i].toLowerCase()
    }
    name += str[i]
  }
  return name
}

console.log(swap('Peter'))

I am not sure whether the problem is in this line.

if(str[i] >= 'a' && str[i] <= 'z'){
  str[i].toUpperCase()
}

Can anyone help me , thanks!!

like image 480
wibbly Avatar asked Oct 14 '25 18:10

wibbly


2 Answers

I think your problem is to think that str[i].toUpperCase() or str[i].toLowerCase() will change the value of the str[i], but it doesn't. These functions will change the char value to uppercase or lowercase and they'll return the result of the function call, but the original variable (str[i]) will remain its value.

Try with this version:

function swap(str) {
  var name = ''
  var string;
  for (i = 0; i <= str.length - 1; i++) {
    string = str[i];  
    if (str[i] == string.toUpperCase()) {
      name += string.toLowerCase();
    } else {
      name += string.toUpperCase();
    }
  }
  return name;
}

console.log(swap('PeTeR'));
like image 129
cooper Avatar answered Oct 17 '25 09:10

cooper


Use reduce to accumulate your new string and lowercase/upercase JS functions to check your letters hence do the conversion.

const swap = (str) => str.split('').reduce((acc, char) =>
  acc += char === char.toLowerCase() ? char.toUpperCase() :
  char.toLowerCase(), '')

console.log(swap('Peter'))
like image 26
Eugen Sunic Avatar answered Oct 17 '25 09:10

Eugen Sunic