Borislav Hadzhiev
Fri Nov 19 2021·2 min read
Photo by Brooke Cagle
To replace the underscores with spaces and capitalize the words in a string:
function toTitleCase(str) { const arr = str.split('_'); const result = []; for (const word of arr) { result.push(word.charAt(0).toUpperCase() + word.slice(1)); } return result.join(' '); } console.log(toTitleCase('a_b_c')); // 👉️ "A B C" console.log(toTitleCase('one_two_three')); // 👉️ "One Two Three"
We created a reusable function, which takes a string, replaces all of the underscores with spaces, and capitalizes each word.
The only parameter we passed to the String.split method is the separator we want to split the string on.
// 👇️ ['a', 'b', 'c'] console.log('a_b_c'.split('_'));
split()
method splits the string on each occurrence of the provided separator and returns an array containing the results.The next step is to iterate over the array, capitalize the first letter of each word and push the string to an array.
The String.charAt method takes an index as a parameter and returns the character at the provided index.
The only parameter we passed to the String.slice method is the start index - the index of the first character to be included in the string.
If we only pass a single parameter to the slice()
method it includes the
characters to the end of the string.
We capitalize the first character of the string and concatenate the rest.
toLowerCase()
method after calling slice()
.function toTitleCase(str) { const arr = str.split('_'); const result = []; for (const word of arr) { result.push(word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() // 👈️ lowercase remainder ); } return result.join(' '); } console.log(toTitleCase('a_b_c')); // 👉️ "A B C" console.log(toTitleCase('oNE_twO_three')); // 👉️ "One Two Three"
The last step is to call the Array.join method and join the array with a space separator.
// 👇️ "a b c" console.log(['a', 'b', 'c'].join(' '));
The only parameter the join()
method takes is the separator, by which we want
to join the array elements into a string.
The new string contains a space at the place of each underscore and has each word capitalized.