Home > front end >  UpperCase the even index of a string
UpperCase the even index of a string

Time:12-22

i am trying to UpperCase() the even indexes of a string;

input: hello world;

output: HeLlO WoRlD;

somehow its not working, i think it is because i cannot mutate a string since it is returning the initial value. Can someone help me solve this problem ?

/* Alternating Caps Write a function that takes in a string of letters and returns a sentence in which every other letter is capitalized.

Example input: "I'm so happy it's Monday" Example output: "I'M So hApPy iT'S MoNdAy" */

function altCaps(str){
let string = str
for(let i = 0; i < str.length; i  ) {
    if(i % 2 === 0) {
       string[i].toUpperCase()
    }
}
console.log(string)

}

CodePudding user response:

Strings are immutable, you need to create a new string and append the letters one by one.

function altCaps(oldStr){
  let newStr = '';
  for(let i = 0; i < oldStr.length; i  )
    newStr  = i % 2 === 0 ? oldStr[i].toUpperCase() : oldStr[i];
  return newStr;
}
console.log(altCaps("I'm so happy it's monday"))

Notice this isn't attempting to mutate newStr, it's getting a new string reassigned for every letter we append.

CodePudding user response:

function altCaps(text,mode=0) {
    return text.split('').map((c,i) => 
        i % 2 == mode ? c.toLowerCase() : c.toUpperCase()
    ).join('');   
}

console.log(altCaps("I'm so happy it's Monday",1));

CodePudding user response:

The problem with your solution is that .toUpperCase() doesn't modify the string it's called on. Rather, it returns a new upper-cased string.

Here's one way the problem could be solved:

const test = "Hello World";
const toAltCase = s => s.split("")
                        .map((c, i) => (i % 2 != 0)?
                          c.toLowerCase() : 
                          c.toUpperCase())
                        .join("");

console.log(toAltCase(test), "<-", test);

  • Related