Basic Algorithm Scripting: Title Case a Sentence(One letter gets replaced)

Tell us what’s happening:

I am trying to solve the challenge: Basic Algorithm Scripting: Title Case a Sentence. I am not using the function syntax for now, i am trying to solve the Problem without the function call but by simple String replace. But what I am getting is the ’ Final String: I’m a little tea Pot ’ i.e. only the first character of last string gets replaced.

Can anybody suggest anything?

Your code so far

var str="I'm a little tea pot";
var newStr="";

// read each character in a string
for (var i = 0; i< str.length; i++) {
	// console.log(str[i]);
	if(str[i] === " ") {
		// read the first character after space
		// console.log("first character after space:" + str[i+1])

		// make the first character after space capital
		// console.log("Capital the first character after space: " + str[i+1].toUpperCase())

		// replace the first character after space with the Capital of the same.
		// console.log("Replace character: " + str.replace(str[i+1], str[i+1].toUpperCase()))
		// console.log((str[i]=str[i+1]).toUpperCase())

		// store the new string in another variable.

		// str += str.replace(str[i+1], str[i+1].toUpperCase());
		// replace each character after space with Captial letter(manually)

		var newStr = str.replace(str[i+1], str[i+1].toUpperCase())
// print the String
console.log("Final String: " + newStr);

EXPECTED OUTPUT: Final String: I’m A Little Tea Pot
ACTUAL OUTPUT: Final String: I’m a little tea Pot(pot becomes Pot)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36.

Challenge: Title Case a Sentence

Link to the challenge:

Add the following as the last two lines within the for loop, so you can have a better idea what is happening at the end of each iteration.

console.log('i = ' + i);

HINT #1: The current way you are using replace will only replace the first occurrence of the character located at str[i+1].

HINT #2: You are overwriting the value of newStr during each iteration by replacing a character of str with the uppercase version of the character. This means only the last replacement gets stored in newStr after the loop ends. Think about what you should initialize newStr to before the loop and what variable you should be applying the replace method to inside the loop.