Title Case, passes all but one

Hi everyone

my code passes all the tests but this string "I'm a little tea pot " not it return"I'I A Little Tea Pot".

here my code:

function titleCase(str) {
  let arr = str.toLowerCase().split(" ");
  let upper = arr.map(a => a[0].toUpperCase());
  let newArr = [];
  for(let i = 0; i < arr.length; i++){
    let newOne = arr[i].replace(/\b\w/g, upper[i]);
    newArr.push(newOne);
  }
  return newArr.join(" ");
}

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

what should i alter in RegExp to pass all the tests?

I suggest you check your code with this tool to see if it is what you want to happen: http://pythontutor.com/javascript.html#mode=display

Also, you may notice that you don’t need the loop, but you could make it work already with the first map method

1 Like

I solve it replacing the regexp /\b\w/g with arr[i][0], thank you so much :slight_smile: :blush:

I think that for loop is necessary even if we use map because I use it itself without for loop and it doesn’t work? please, can you suggest some code without using for loop?

@ilenia yes you’re right, I found it, thanks a lot for your help :slight_smile:

here is the code:


function titleCase(str) {
  let arr = str.toLowerCase().split(" ");
  let upper = arr.map(a => a.replace(a[0], a[0].toUpperCase()) );
  for(let i = 0; i < arr.length; i++){
	let newArr = upper.join(" ");
	return newArr;
  }

}

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

Now you have a loop that is not executed… remember that a return statement breaks from the function - remove the loop and move the return statement outside of it

1 Like

yes you’re right there is no need for for loop here, thank you so much :slight_smile: