How do I change the iterable variable while running a loop

Hello, campers!

I am trying to solve this exercise.

I am trying to avoid solving it with RegEx. Hence, this is my approach:

function titleCase(str) {
  let new_str = "";

  for (let i in str) {
    //console.log(str[i],  i, new_str);
    if (str[i]==" ") {
      new_str=new_str+" "+ String(str[parseInt(i)+1]).toUpperCase()
      i++;
    }
    else {
        new_str=new_str+String(str[i]);
        
    }
  }
  return new_str;
}

console.log(titleCase("I'm a little tea pot"));

This code returns the result bellow which is almost right:

I'm Aa Llittle Ttea Ppot

I tried to avoid this error making the for loop jump an iteration with:

      i++;

However, the iteration variable “i” seems to be immutable.

How can I solve this?

I don’t think that the i++ will work in a for...in loop. You don’t really want to be using a for...in loop anyway.

If you’re going to be doing funky things with the iterator, you probably want to just use a traditional for loop.

There are an infinite number of ways to skin this cat, but the easiest ones start out by splitting the string into an array of individual words. That might help.

Don’t use for…in for strings: it is specifically for iterating over objects.

You can use a for loop. This will work, to a degree (you haven’t handled the first character unless the first character/s are spaces).

for (let i = 0; i < str.length; i++) {
  newStr += str[i];

You can also use a for…of loop, which is designed for iterating over iterables (strings, arrays, maps, sets).

for (let char of str) {
  newStr += char;

Whichever construct you use, to handle the uppercasing, I would store the previous character rather than peeking at the next one.

So declare a variable (let prevChar = " ";, EDIT this needs to be a space character, so that the first character of the string always gets uppercased). If the prev character is a space, then uppercase the character you add, otherwise just add the character. Then store the current character as the previous character after that check.

This is unnecessary, a string is already a string, you don’t need to convert it to one.

2 Likes

Nice. Here it goes:

function titleCase(str) {
  let lower_str = str.toLowerCase();
  //console.log(lower_str);
  let new_str = "";

  for (let i in lower_str) {
    //console.log(str[i],  i, new_str);
    if (str[parseInt(i)-1]==" ") {
      //console.log(str[i],i);
      new_str=new_str+ lower_str[parseInt(i)].toUpperCase()
    }
    else if (i==0) {
      new_str=new_str+ lower_str[parseInt(i)].toUpperCase()
    }
    
    else {
        new_str=new_str+lower_str[i];
    }
  }
  return new_str;
}

Thanks, @DanCouper!

1 Like