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 letters after the first letter.
function titleCase(str) {
var newstr = str.split(" ");
for(i=0;i<newstr.length;i++){
newstr[i].charAt(0).toUpperCase();
}
newstr = newstr.join(" ");
return newstr;
}
To be clear, I want every single word in the sentence to be capitalized.
If you enjoy using Ramda like I do, you can do this clean fun thing:
import { concat, compose, head, join, map, split, tail, toLower, toUpper } from 'ramda';
const toWords = split(' ');
const capitalizeWords = map(s => concat(toUpper(head(s)), toLower(tail(s))));
const toSentence = join(' ');
const toTitleCase = compose(toSentence, capitalizeWords, toWords);
or of course you can always cut it down to
const capitalizeWords = map(s => concat(toUpper(head(s)), toLower(tail(s))));
const toTitleCase = compose(join(' '), capitalizeWords, split(' '));
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.
This should work. Notice how I set newstr[i]
to the desired output. Functions like .toUpperCase()
do not affect the original string. They only return a new string with the desired property.
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;
}
Here is a working piece of code. The problematic line in your code was this one:
newstr[i].charAt(0).toUpperCase();
That line gets the uppercased first letter of each word, but it doesn't do anything with it. The way the code below works is that it uppercases the first character, then appends the rest of the word, then assigns that back into newstr[i]
.
function titleCase(str) {
var newstr = str.split(" ");
for(i=0;i<newstr.length;i++){
newstr[i] = newstr[i].charAt(0).toUpperCase() + newstr[i].substring(1).toLowerCase();
}
newstr = newstr.join(" ");
return newstr;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With