1

I need to make a function that reads a string input and converts the odd indexed characters in the string to upperCase and the even ones to lowerCase.

function alternativeCase(string){
    for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
            string[i].toUpperCase();
        }
        else {
            string[i].toLowerCase();
        }   
    }
    return string;
}

How to fix my code?

1

4 Answers 4

5
function alternativeCase(string){
  return string.split('').map(function(c,i) {
    return i & 1 ? c.toUpperCase() : c.toLowerCase();
  }).join('');
}

Update 2019

These days it's pretty safe to use ES6 syntax:

const alternativeCase = string => string.split('')
  .map((c,i) => i & 1 ? c.toUpperCase() : c.toLowerCase()).join('');
0

Try this:

function alternativeCase(string){
    var output = "";
    for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
            output += string[i].toUpperCase();
        }
        else {
            output += string[i].toLowerCase();
         }   
    }
    return output;
}
2
  • Thank you! This worked for me perfectly! I was not that far off with my code!
    – Ann0nym
    Jan 4, 2017 at 11:21
  • nope you werent far off, you were close! As other comments mentioned, strings in JS are "Immutable" which means they can't be changed in memory without assigning it to a new variable (or itself), which is why you couldn't set a character within the string the way you were. That was the only problem with your method.
    – Alex
    Jan 4, 2017 at 16:07
0

Strings in JavaScript are immutable, Try this instead:

function alternativeCase(string){
     var newString = [];
     for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
           newString[i] = string[i].toUpperCase();
        }
        else {
           newString[i] = string[i].toLowerCase();
        }   
     }
   return newString.join('');
}

0

RegExp alternative that handles space between characters :

const alternativeCase = s => s.replace(/(\S\s*)(\S?)/g, (m, a, b) => a.toUpperCase() + b.toLowerCase());

console.log( alternativeCase('alternative Case') )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.