Created
July 21, 2017 14:54
-
-
Save jsmayo/df6f9508791d502c6e51a0529ae2a92b to your computer and use it in GitHub Desktop.
Title Case a Sentence W/ JS:
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
Examples: | |
------------------------------------------------------------ | |
Split and loop method: | |
------------------------------------------------------------ | |
function titleCase(str) { | |
var newstr = str.split(" "); | |
for(i=0;i<newstr.length;i++){ | |
if(newstr[i] == "") continue; | |
var copy = newstr[i].substring(1).toLowerCase(); | |
newstr[i] = newstr[i][0].toUpperCase() + copy; | |
} | |
newstr = newstr.join(" "); | |
return newstr; | |
} | |
titleCase("I'm a little tea pot"); | |
------------------------------------------------------------ | |
Mapping: | |
------------------------------------------------------------ | |
function titleCase(str) { | |
/* Get everything in LC format, split by spaces, | |
and map each word from the split to return an uppercase | |
from the index 0 character that's concatinated with a | |
split from index 1 to the end of the array */ | |
return str.toLowerCase().split(' ').map(function(word) { | |
return (word.charAt(0).toUpperCase() + word.slice(1)); | |
}).join(' '); | |
} | |
titleCase("I'm a little tea pot"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment