Reputation: 89
I'm going through freeCodeCamp and am stuck on their "Basic Algorithm Scripting: Title Case a Sentence" challenge. My code seems to output correctly, but freeCodeCamp is not passing me. Any help or insights into what may be the cause of the issue would be much appreciated!
Here are their instructions:
Here is my solution:
function titleCase(str) {
var strArray = str.split(' '); // make string into an array
var finalSentence = ''; // initialize variable for the final 'Title Cased' sentence
// loop through each element in the array
for (var i = 0; i < strArray.length; i++) {
// get the length of each array element
var strLength = strArray[i].length;
// convert first letters of each word to upper-case
finalSentence += strArray[i].charAt(0).toUpperCase() +
// convert remaining letters of each word to lower-case
strArray[i].substring(1,strLength).toLowerCase() +
// add space between words
" ";
}
return finalSentence;
}
// string to test
titleCase("I'm a little tea pot");
My output reads "I'm A Little Tea Pot", which is what the instructions asked for. The other inputs that the instructions asked me to test all output correctly as well...
Upvotes: 0
Views: 500
Reputation: 1
function titleCase(str) {
const arr = [];
let addUpper = true;
str.split("").forEach(e =>{
if(addUpper){
arr.push( e.toUpperCase());
addUpper = false;
}else{
arr.push(e.toLowerCase());
}
if(e === " "){
addUpper = true;
}
})
return(arr.join(""));
}
titleCase("I'm a little tea pot");
Upvotes: 0
Reputation: 11
First I explain what is the wrong in your code,
In your code,
finalSentence += strArray[i].charAt(0).toUpperCase() + strArray[i].substring(1,strLength).toLowerCase() + " ";
In the last, you add " " to add space between words. Thus, after every word, it will add " ". So, you can get the output for titleCase("I'm a little tea pot");
like this, "I'm A Little Tea Pot " not "I'm A Little Tea Pot". See, there is an additional " " (space) in your coding output.
You can add " " like this,
finalSentence += strArray[i].charAt(0).toUpperCase() + strArray[i].substring(1,strLength).toLowerCase();
if(i < strArray.length - 1){
finalSentence += " ";
}
This is another easy way to do this challenge,
function titleCase(str) {
let strArr = str.toLowerCase().split(' ');
for (var i = 0; i < strArr.length; i++) {
strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1);
}
return strArr.join(' ');
}
titleCase("I'm a little tea pot");
Good Luck!. Thank you :)
Upvotes: 0
Reputation: 321
Try this.
function titleCase(str) {
var ret = "";
var upperCase = true;
for (var i = 0; i < str.length; i++) {
var chr = str.charAt(i);
if(upperCase) {
ret += chr.toUpperCase();
}
else{
ret += chr.toLowerCase();
}
upperCase = chr == " ";
}
console.log(ret);
}
titleCase("I'm a little tea pot");
titleCase("sHoRt AnD sToUt");
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT");
Upvotes: 0