Objective
Create a function to convert a camel-cased string into title case.
Description
In the exercise JavaScript Strings — Camel Words, we implemented the function getWords()
to extract out all the words from a given camel-cased string into an array.
In this exercise, you have to create a function camelToTitleCase()
that converts a given camel-cased string into title case using the getWords()
function.
As per the title case convention, the words obtained from the camel-cased string must be separated by a space and have the first word's first letter in uppercase.
So for instance, if the string passed to camelToTitleCase()
is 'firstChild'
, where the words are first
and Child
, the function must return back the string 'First Child'
.
Note that if the given string is empty, the function must return back an empty string as well.
Shown below are a couple more examples:
camelToTitleCase('insertHTML')
'Insert HTML'
camelToTitleCase('insertAdjacentHTML')
'Insert Adjacent HTML'
camelToTitleCase('firstHTMLElement')
'First HTML Element'
camelToTitleCase('releaseDate')
'Release Date'
camelToTitleCase('')
''
New file
Inside the directory you created for this course on JavaScript, create a new folder called Exercise-30-Camel-To-Title and put the .html solution files for this exercise within it.
Solution
Since we are instructed to use the getWords()
function, that we created back in the JavaScript Strings — Camel Words exercise, our job becomes very very simple.
We just ought to process the array returned by getWords()
as called on the string argument given to camelToTitleCase()
and then join it using the join()
array method.
That's it!
Consider the following definition of camelToTitleCase()
:
function getWords(str) { /* ... */ }
function camelToTitleCase(str) {
if (str === '') {
return '';
}
var words = getWords(str);
// Uppercase the first letter of the first word.
words[0] = words[0][0].toUpperCase() + words[0].slice(1);
return words.join(' ');
}
If str
is ''
, we immediately return ''
, as per the description of the exercise.
Beyond this point, we call getWords(str)
to obtain a list of all the words in str
and then uppercase the first word's first letter (since it's the only word with its first character in lowercase; rest of the words all have their first letters in uppercase).
Finally, we join all the words with the space character in between, using the array join()
method.
And this completes this exercise.