I\'m trying to proper case a string in javascript - so far I have this code: This doesn\'t seem to capitalize the first letter, and I\'m also stuck on how to lowercase all the l
function titleCase(str){
var strToArray = str.split(" ");
var newArray = [];
for(var i=0; i < strToArray.length; i++){
var element = strToArray[i].replace(strToArray[i][0], strToArray[i][0].toUpperCase());
newArray.push(element);
}
return (newArray.join(" "));
}
One of the cleanest ways I can come up with, using ES6, while still lacking a proper .capitalize()
string prototype method:
let sent = "these are just some words on paper"
sent.split(' ').map ( ([h, ...t]) => h.toUpperCase() + t.join('').toLowerCase() )
Uses destructuring on array element strings to obtain head and tail via spread operator (making tail a sequence of characters) which are first joined before coerced to lower case. Or you could replace that with a s => s[0].toUpperCase() + s.substring(1).toLowerCase()
I guess. Oh, since the question seems to indicate ES5, transformation is cheap although noticeably more verbose:
function capitalize (sentence) {
return sentence.split(' ').map(
function (s) {
return s[0].toUpperCase() + s.substring(1).toLowerCase()
}).join(' ') ;
}
That is, assuming you'd want another sentence returned.
function titleCase(str) {
var newArr = str.toLowerCase().split(" "),
firstLetter,
updArr = [];
for(var i=0;i<newArr.length;i+=1){
firstLetter = newArr[i].slice(0,1);
updArr.push(newArr[i].replace(firstLetter, firstLetter.toUpperCase()));
}
return updArr.join(" ");
}
First all become lowercase, and then open each word, and then open each letter, the first letter set capital, and then together
function titleCase(str) {
var copy=str;
copy=copy.toLowerCase();
copy=copy.split(' ');
for(var i=0;i<copy.length;i++){
var cnt=copy[i].split('');
cnt[0]=cnt[0].toUpperCase();
copy[i]=cnt.join('');
}
str=copy.join(' ');
return str;
}
titleCase("I'm a little tea pot");
My Solution
function titleCase(str) {
var myArr = str.toLowerCase().split(" ");
for (var a = 0; a < myArr.length; a++){
myArr[a] = myArr[a].charAt(0).toUpperCase() + myArr[a].substr(1);
}
return myArr.join(" ");
}
function titleCase(str) {
var titleStr = str.split(' ');
for (var i = 0; i < titleStr.length; i++) {
titleStr[i] = titleStr[i].charAt(0).toUpperCase() + titleStr[i].slice(1).toLowerCase();
}
return titleStr.join(' ');
}
titleCase("i'm a little tea pot")