Skip to content

Instantly share code, notes, and snippets.

@jsmayo
Created July 21, 2017 14:54
Show Gist options
  • Save jsmayo/df6f9508791d502c6e51a0529ae2a92b to your computer and use it in GitHub Desktop.
Save jsmayo/df6f9508791d502c6e51a0529ae2a92b to your computer and use it in GitHub Desktop.
Title Case a Sentence W/ JS:
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