Replace underscores with spaces and capitalize words in JS

avatar

Borislav Hadzhiev

Fri Nov 19 20212 min read

banner

Photo by Brooke Cagle

Replace underscores with spaces and capitalize words #

To replace the underscores with spaces and capitalize the words in a string:

  1. Split the string on each underscore.
  2. Iterate over the array of words and capitalize the first letter of each word.
  3. Push the results to an array.
  4. Join the array elements with a space separator.
index.js
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.

index.js
// ๐Ÿ‘‡๏ธ ['a', 'b', 'c'] console.log('a_b_c'.split('_'));
The 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.

If you want to make sure that the remainder of the string is lowercase, you can call the toLowerCase() method after calling slice().
index.js
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.

index.js
// ๐Ÿ‘‡๏ธ "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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee