skip to Main Content

I am solving this code wars kata problem that requires me to return a string in a weird case such that the first letter is in uppercase and the next is in lowercase and so on.

Here is the link to the question

I came up with this code:

function toWeirdCase(string){
  var r = string 
  let  newString = [];
    for( let i in string ) {
        if(i%2 == 0){
            newString.push(string[i].toUpperCase());
        } else {
            newString.push(string[i].toLowerCase());
        }
    }
    return newString.join('');
  
}

I am stuck because I cannot be able to account for the space and I need the next word to start with a capital letter.

2

Answers


  1. Instead of doing it char by char, which will introduce a few unnecessary ifs. (since you can’t just look for odd/even letters, you have to take into account spaces and new words). You can start by splitting the string into words. and then work on each word separately. That way there are less rules, you start with the Uppercase every time, and after you finish that, just join them again. Something like this:

    function toWeirdCase(string) {
        return string.split(' ')
            .map(word => word.split('')
                .map((c, i) => i % 2 === 0 ? c.toUpperCase() : c.toLowerCase())
                .join(''))
            .join(' ')
    }
    
    Login or Signup to reply.
  2. Here’s a solution based on your approach where you .split() the input string first into separate words before performing the actual capitalization of each char.

    function toWeirdCase(string) {
      const words = string.split(' ');
      const modifiedWords = [];
    
      for (const word of words) {
        let newString = '';
    
        for (let i in word) {
          if (i % 2 === 0) newString += word[i].toUpperCase();
          else newString += word[i].toLowerCase();
        }
    
        modifiedWords.push(newString);
      }
    
      return modifiedWords.join(' ');
    }
    
    console.log(toWeirdCase("String")); // "StRiNg"
    console.log(toWeirdCase("Weird string case")); // "WeIrD StRiNg CaSe"
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search