# Algorithm Challenge - Title Case a Sentence

Hello,

I’ve just completed the “Title Case a Sentence” algorithm challenge, and although I found it reasonably easy in terms of logic, I’m wondering if there is a cleaner way to approach the solution compared to the code that I have written. My solution was:

``````function titleCase(str) {

// return an array containing all words in str, converted to lower case
var map1 = str.split(" ").map(function(val) {
return val.toLowerCase();
});

// return an array containing all words in map1, with the first letter capitalized
var map2 = map1.map(function(val) {
var firstUpper = val[0].toUpperCase();
var valRemain = val.slice(1);
return firstUpper.concat(valRemain);
});

// return map2 as a string
return map2.join(" ");
}

titleCase("I'm a little tea pot");
``````

Is there a cleaner way of doing this? Or is my solution ok in terms of code best practice/readability?

Any feedback is very welcome.

Thanks!

You could do it in a single map function by `toUpperCase`ing the first letter and `toLowerCase`ing the remainder instead of making one pass through to lowercase it and another pass through to capitalize the first letter.

1 Like

Hi!
I found this solution Here.

``````function toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
``````
1 Like

Because @th3s0ysauc3 didn’t ask to see other solutions, I have added a spoiler blur to your post.

Thanks both! I’m going to refactor by using a single map function.

It appears that some sleep has helped me solve this quickly using only a single map function:

``````function titleCase(str) {
var map = str.split(" ").map(function(val) {
return val[0].toUpperCase() + val.slice(1).toLowerCase();
});
return map.join(" ");
}

titleCase("I'm a little tea pot");
``````

Thanks for the guidance!