solved the challenge “Title Case a String” without using replace(). Please anyone let me know is it correct or have any issues.
function titleCase(str) {
let newstr = str.toLowerCase().split("");
for(var i=0;i<newstr.length;i++){
newstr[0]=newstr[0].toUpperCase();
if(newstr[i]==" "){
newstr[i+1]=newstr[i+1].toUpperCase();
}
}
let final = newstr.join("");
return final;
}
titleCase("I'm a little tea pot");
Your code does work, but I would recommend not bothering with making an entire array because a String can already be iterated over like an Array as example this function would also get the job done :
function titleCase(str) {
let s = ${str[0].toUpperCase()};
for (let i = 1; i < str.length; i++) {
s = ${s}${str[i - 1] === ' ' ?
str[i].toUpperCase() :
str[i].toLowerCase()}
}
return s
}
I am using template literals which require back-ticks so unfortunately that does not work very well because back-ticks are used to write code in here.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.