Given the two solutions, I think the second is stylistically a better way to do things in javascript for the reason that solution 1 is using the for loop which is not using the power of javascript as a functional programming language. An alternative modification of solution 2 would be make everything one statement and never change the value of str but instead return the value:
function titleCase(str) {
return str.toLowerCase()
.split(" ")
.map(function(v){return v.charAt(0).toUpperCase() + v.slice(1)})
.join(" ");
}
This modification means that the function will not mutate any variables. As for performance, the first solution runs slightly faster on my system using nodejs.
function time_it (fn, arg, n) {
var time = Date.now()
for(var i = 0; i < n; ++i) {
fn(arg);
}
return Date.now() - time;
}
SENTANCE = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis augue consequat, ullamcorper ipsum in, scelerisque tortor. Nulla justo dolor, ultrices ac varius a, fringilla et nisi. Vestibulum tristique euismod turpis, sed fermentum nibh rutrum tempus. Fusce a metus tincidunt, convallis lectus sed, suscipit ipsum. Duis sagittis et dolor id dapibus. Morbi quam urna, tristique non bibendum sit amet, viverra eget magna. Duis felis nisi, sodales eu ante et, vulputate pellentesque sem. Integer luctus lacus blandit, euismod dui vel, ultrices nibh. Suspendisse potenti. Phasellus bibendum, quam sit amet vehicula dapibus, nunc augue blandit sapien, nec bibendum purus elit at turpis."
console.log("titleCase_1 (ms): " + time_it(titleCase_1,SENTANCE,100000))
console.log("titleCase_2 (ms): " + time_it(titleCase_2,SENTANCE,100000))
console.log("titleCase_3 (ms): " + time_it(titleCase_3,SENTANCE,100000))
The results
titleCase_1 (ms): 2688
titleCase_2 (ms): 4391
titleCase_3 (ms): 4364
This has to do with the line
val.charAt(0).toUpperCase() + val.slice(1);
and the fact that solution 1 doesn't make copies of the str in the loop like map does.
An argument in favor of the second solution is that its performance could be much better. Likely what is happening is the map function is running serially but in many functional languages the map function can or is parallelized automatically.
map()
-based solutions (your Solution 2 and breckwagner's) are slower by 25%. On Firefox 42, your Solution 1 and Greg Burghardt's regex are slower by 25%. So, pick the solution you find the most elegant. \$\endgroup\$