Created
June 21, 2016 14:10
-
-
Save brainyfarm/1fc1899976f33afce52d1e3095b4183f to your computer and use it in GitHub Desktop.
Olawale/FreeCodeCamp Algorithm: Title Case a Sentence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function titleCase(str) { | |
return str.split(" ").map(function(each){ | |
return each.replace(each.charAt(0),each.charAt(0).toUpperCase()).replace(each.substr(1,each.length), each.substr(1,each.length).toLowerCase()); | |
}).join(" "); | |
} | |
titleCase("I'm a littLe tea pot"); | |
/** | |
My Old solution below | |
function titleCase(str) { | |
// Convert the whole string into lowercase then split it into an array with each word as an element | |
var strArray = str.toLowerCase().split(" "); | |
// Create an empty array to keep each word when successfuly converted | |
var newSentence = []; | |
// Do a for loop on the array containing each word | |
for(i=0;i<strArray.length;i++){ | |
// Convert the first character of the item at the present iteration into uppercase with str.replace() | |
//When done, push the word into the newSentence array | |
newSentence.push(strArray[i].replace(strArray[i].charAt(0), strArray[i].charAt(0).toUpperCase())); | |
} | |
// Join the new sentence array into a string and return it | |
return newSentence.join(" "); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment