Recursive Function to Capitalize Words in an Array

Every once in a while, someone writes something bullet proof in as little as a couple lines. Here’s something I got off code academy that I thought might be useful to people:

// Our array of messy words
var capitals = ["berlin", "parIs", "MaDRiD"];

// Capitalize function
function capitalize(word) {
  return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}

// Our recursive function
function fixLetterCase(array, i) {    
  // Base case
  if (i === array.length) {
    return;
  } 
  // Action
  array[i] = capitalize(array[i]);
  $('p').append(array[i] + '<br />');
  
  // Recursive case
  return fixLetterCase(array, i + 1);
}

// Here is our function call
fixLetterCase(capitals, 0);

See the Pen oXLydm by Mike Newell (@newshorts) on CodePen.

There are two things going on here, the “capitalize” function, which takes any string and capitalizes the first letter, then lower cases the rest of the string by slicing it at “1”. The other function is a recursive function that iterates through all the elements in the initial array and runs the capitalize function on every single one.

The bullet proof part is the “capitalize” function, it will work on almost any situation where a string is passed to the function without counting letters, character by character. It let’s JavaScripts native string functions do all the work. Very well written.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.