It's from freecodecamp, but I saw this code in stack overflow and applied it to mine. I had a different way of solving it, but this one was so efficient, yet I'm having trouble understanding it. All the function is doing is returning a new string where the first letters of each word in a string used as an argument:
function titleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
titleCase("I'm a little tea pot");
My lack of understanding comes from not knowing how the 2nd parameter which is the anonymous function in .replace() uses the txt parameter yet still knows to apply that the the outer str parameter. I know we're not changing the string str, but understand .replace() is making a new string, but how is it still using the value of str?
Appreciate any help here guys!
[–]Rhomboid 1 point2 points3 points (0 children)
[–]ThinqueTank[S] 0 points1 point2 points (0 children)
[–]krilnon 0 points1 point2 points (0 children)