I want to convert the given string to a title case:
const titleCase = function (text) { if (text === "") return ""; let textArr = text.split(" "); const outputArr = textArr.map( ele => ele.toLowerCase().replace(ele[0], ele[0].toUpperCase()) ); const output = outputArr.join(" "); return output; }; const test1 = titleCase("this is an example"); const test2 = titleCase("WHAT HAPPENS HERE"); console.log(test1); console.log(test2);
test1
gives me the right result This Is An Example
but test2 returns what happens here
which is not the result that I want.
I am confused… where did it go wrong?
Advertisement
Answer
When you run it on the test2
string, each ele
in your map function is the upper case word. When you attempt to replace ele[0]
in your function, it is looking for the upper case character in a string that has no upper case letters. ie with ‘WHAT’ you’re looking to replace ele[0]
which is W
in the string what
.
Try:
ele => ele.toLowerCase().replace(ele[0].toLowerCase(), ele[0].toUpperCase())