简体   繁体   中英

Function that returns the opposite letter

I want to write a function that returns alternating characters, so for instance:

"hello world".toAlternatingCase() === "HELLO WORLD"
"HELLO WORLD".toAlternatingCase() === "hello world"
"HeLLo WoRLD".toAlternatingCase() === "hEllO wOrld"

Here is my try

const alternatingCase = function (string) {
  let newword = "";

  for (i = 0; i<string.length; i++) {
     if (string.charAt(i).toUpperCase())
    {
    newword+= string.charAt(i).toLowerCase()
    }

   else 
   {
   newword+=string.charAt(i).toUpperCase()
   }
  }
  return newword  
}

When invoked, the function unfortunately only returns the string itself, not sure what I'm doing wrong though, thanks very much for reading or even helping out!

You need to check if the caracter is uppercase and take then lower case.

Don't forget to declare all variables.

This approach uses a conditional (ternary) operator ?: where a condition is used to return two different expressions.

 const alternatingCase = function(string) { let newword = ""; for (let i = 0; i < string.length; i++) { let character = string[i]; newword += character === character.toUpperCase()? character.toLowerCase(): character.toUpperCase(); } return newword; } console.log(alternatingCase('Test'));

If you really need to use the function as prototype of string, you need to assign the function to String.prototype and the wanted method. For this you need to address this , to get the value of the string.

 String.prototype.alternatingCase = function() { let newword = ""; for (let i = 0; i < this.length; i++) { let character = this[i]; newword += character === character.toUpperCase()? character.toLowerCase(): character.toUpperCase(); } return newword; } console.log('Test'.alternatingCase());

you've done the compression wrong

checkout this

 function alternatingCase(string) { let newword = ""; for (i = 0; i < string.length; i++) { const c = string.charAt(i); if (c === c.toUpperCase()){ newword += c.toLowerCase() } else { newword += c.toUpperCase() } } return newword; } console.log(alternatingCase("TesT"));

All you need to update is your condition to if (string.charAt(i) === string.charAt(i).toUpperCase()) . You have to compare your uppercase letter to original letter.

 const alternatingCase = function(string) { let newword = ""; for (i = 0; i < string.length; i++) { if (string.charAt(i) === string.charAt(i).toUpperCase()) { newword += string.charAt(i).toLowerCase() } else { newword += string.charAt(i).toUpperCase() } } return newword } console.log(alternatingCase("HeLLo WoRLD"));

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