skip to Main Content

I would like to alternate cases along the string for more than one word. Every word should start with capital letter. I’ve got stuck in the process and don’t know how sort it out.

Example: input: "hello world" / output: "HeLlO WoRlD"

function alternateCase(str) {

  if (str.length === 0) {
    return ""
  }
  const arrCapitalised = []

  const splitStr = str.split("")
  const indexSpace = splitStr.indexOf(" ")

  const joinStr = str.split(" ").join("")


  for (let i = 0; i < joinStr.length; i++) {
    if (i % 2 === 0) {
      arrCapitalised.push(joinStr[i].toUpperCase())
    } else {
      arrCapitalised.push(joinStr[i])
    }
  }
  console.log(arrCapitalised, "PREVIOUS ARRAY")
  const finalArr = arrCapitalised.splice(indexSpace, 0, " ")
  console.log(finalArr, "FINAL ARRAY")
  return arrCapitalised.join("").toString()
}

5

Answers


  1. eAsY…

    console.log( alternateUpDown( 'hello world !' ));
    
    function alternateUpDown( str )
      {
      const ope = [ (s)=>s.toUpperCase(), (s)=>s.toLowerCase() ];
      let i_Ope = 0, res = '';
      
      for (l of str)
        {
        res += ope[i_Ope](l);
        i_Ope = ++i_Ope %2;
        }
      return res
      }

    a shorter one…

    console.log( alternateUpDown( 'hello world !' ));
    
    function alternateUpDown( str )
      {
      const ope = [ (s)=>s.toUpperCase(), (s)=>s.toLowerCase() ];
      return Array.from(str,(c,i)=>ope[i&1](c)).join();
      }
    Login or Signup to reply.
  2. Here is is:

    I transformed the word into an array of characters, then looped once through it and used the upper case into the even letters.

    function alternateCase(str) {
        const words = str.split(' ');
        const result = [];
        
        words.forEach((word) => {
            Array.from(word).forEach((letter,idx) => {
                if (idx % 2 === 0) {
                    result.push(letter.toUpperCase());
                } else {
                    result.push(letter);
                }
            })
            result.push(' ');
        })
        return result.join('');
    }
    
    console.log(alternateCase('hello world test test test'))
    Login or Signup to reply.
  3. Use of a parsing function gives the most stable result imho. The snippet takes words from a string (the start of a word defined as a letter not preceded by any letter) and converts anyting up to the next ‘not letter’. The first letter is converted to uppercase, the rest of the word to letters with alternating case (the current case of a letter doesn’t matter, see second example)

    const someStr = `hello world and universe`;
    const anotherStr = `helLO wOrld!and UnIverse`;
    
    console.log(alternateCase(someStr));
    console.log(alternateCase(anotherStr));
    
    function alternateCase(someString) {
      const str = [...someString];
      const isUpper = l => l.toUpperCase() === l;
      let prev;
      let result = ``;
      
      while (str.length) {
        let chr = str.shift();
        result += !prev || !/p{L}/iu.test(prev) || !isUpper(prev)
          ? chr.toUpperCase() : chr.toLowerCase();
        prev = result.at(-1);
      }
      
      return result;
    }
    Login or Signup to reply.
  4. You could toggle the function for changing the charater and reset if a space is found.

    function alternateCase(string) {
        const
            toggle = { toLowerCase: 'toUpperCase', toUpperCase: 'toLowerCase' };
        let
            method = 'toLowerCase',
            result = '';
            
        for (const c of string) {
            method = c === ' ' ? 'toLowerCase': toggle[method];
            result += c[method]();
        }
        return result;
    }
    
    console.log(alternateCase('hello world'));
    console.log(alternateCase('four letters'));
    Login or Signup to reply.
  5. You can just use a boolean flag for the current case and reset that when you hit a space. Also note that you probably should call .toLowerCase when inserting a lowercase character, to make the function work correctly for non-lowercase inputs.

    function alternateCase(str) {
        let out = '';
        let isUpper = true;
        for(const char of str) {
            if(isUpper)
                out += char.toUpperCase();
            else
                out += char.toLowerCase();
    
            isUpper = char === ' ' || !isUpper;
        }
        return out;
    }
    
    console.log(alternateCase('hello world')) // HeLlO WoRlD
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search