Why does this fail? Should I (somehow) escape letter i — this doesn't fail with other characters.
titleCase("I'm a little tea pot");
// Prints: "i'm A Little Tea Pot"
// Expected: "I'm A Little Tea Pot"
function titleCase(str) {
return str.split(' ').map(function(each) {
return each.toLowerCase().replace(each[0], each[0].toUpperCase());
}).join(' ');
}
The .toLowerCase() is happening on the original value of each, so the .replace() may/will not give you the expected results.
If you split it out as a separate statement, it should work as expected:
function titleCase(str) {
return str.split(' ').map(function(each) {
each = each.toLowerCase();
return each.replace(each[0], each[0].toUpperCase());
}).join(' ');
}
As a slightly more efficient approach, it would also be better to move the .toLowerCase() to before the .map() call so it only needs to be called once, instead of once-per-word:
function titleCase(str) {
str = str.toLowerCase();
return str.split(' ').map(function(each) {
return each.replace(each[0], each[0].toUpperCase());
}).join(' ');
}
You can try something like this:
function titleCase(str) {
return str.split(' ').map(function(each) {
return each.charAt(0).toUpperCase() + each.substring(1).toLowerCase();
}).join(' ');
}
console.log(titleCase("I'm a little tea pot"));
function titleCase(str) {
return str.split(' ').reduce(function(p,c) {
return p + " " + toTitle(c);
});
}
function toTitle(str){
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}
console.log(titleCase("I'm a little tea pot"));
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