I'm new to JavaScript and am having a bit of trouble with this problem:
Construct a function called titleCase that takes a sentence string and gives it title casing.
titleCase("this is an example") // Should return "This Is An Example"
titleCase("test") // Should return "Test"
titleCase("i r cool") // Should return "I R Cool"
titleCase("WHAT HAPPENS HERE") // Should return "What Happens Here"
titleCase("") // Should return ""
titleCase("A") // Should return "A"
This is the code I've tried:
const titleCase = function(text) {
text = text.split(' ');
for (let i = 0; i < text.length; i++) {
text[i] = text[i].toLowerCase().split('');
text[i][0] = text[i][0].toUpperCase();
text[i] = text[i].join('');
}
if (text === "") {
return ""
}
return text.join(' ');
}
It is passing all tests except for the empty string "" test.
if (text === "") { return "" }””.split()return? What are the effects of callingjoinon that result? Experimenting in the console provides a quick way to test assumptions (and code) without having to run a complete program/function/etc.if (text === "")to the first line beforetext = text.split(' ');