The task is to write a JavaScript-function which translates a given blank-separated sentence to title-case.
Means that all words shall start with a capital and then the rest of the word in lower-case. But: A certain, specified set of conjunctions, preposition as well as article shall be all lower-case.
Example: "The second of the four items." becomes "The Second of the Four Items.".
Here's my implementation of such a function:
function translateToTitleCase(str) {
const translateWord = (sWord) => {
return sWord.slice(0, 1).toUpperCase() + sWord.slice(1).toLowerCase();
}
const words = str.split(" ");
words[0] = translateWord(words[0]);
for (let i = 1; i < words.length; i++) {
if (!["of", "and", "the", "to"].includes(words[i].toLowerCase())) {
words[i] = translateWord(words[i]);
} else {
words[i] = words[i].toLowerCase(); // Make sure is's the correct case, when the sentence (or parts of it) is given in uppercase.
}
}
return words.join(" ");
}
// -- Examples -------------------------------------------------------------------------------
console.log(translateToTitleCase("Into unmerciful the entreating stronger to of word guessing."));
console.log(translateToTitleCase("the OLD MAN aND THE sEa"));
I think my coding is still a bit "noisy" with the usage of all those brackets, chained methods and concatenation.
Any ideas about how to improve my implementation?
Perhaps some cool new ES6-feature I wasn't aware of.
What would you have done differently and why?