TitleCase via Apex

Published by Henry Poyntz (Commander-in-Geek at Trausteknik) on 19 Jan 2022

Sadly, the String class built into Salesforce's Apex language does not come with a native "Titlecase" function.

There is however a blog post from Karen on the Explorations Into Salesforce blog that has some code, but there are unfortunately some syntax errors.

Here's an updated version:

   public static String titleCase(String providedString)
   {//originally from: https://explorationsintosalesforce.wordpress.com/2018/02/02/proper-case-and-title-case-methods-for-apex/
       //if we've been given a null or blank string, return it
       if(providedString == null || providedString.trim().length() == 0){return providedString;}
       //the titlecase string we'll eventually return
       String titleCaseString = '';
       //these words should never be made TitleCase
       Set<String> wordsToSkip = new Set<String>{'a','an','and','at','but','for','in','is','nor','of','or','the','to','with','de','la','the','van','von'};
       //split the provided string into a list of strings, using space as the 
       List<String> words = providedString.toLowerCase().normalizeSpace().split(' ');
       for(String word : words)
          //check if we have any scottish friends in our words, or any of the words we are skipping
          if(word.length() > 2 && word.startsWith('mc'))       {titleCaseString += ' Mc' + word.right(word.length()-2).capitalize();}
          else if(word.length() > 3 && word.startsWith('mac')) {titleCaseString += ' Mac' + word.right(word.length()-3).capitalize();}
          else if(wordsToSkip.contains(word))                  {titleCaseString += ' ' + word;}
          else                                                 {titleCaseString += ' ' + word.capitalize();}
       //kill any additional whitespace (there will be one at the start), then return.
       return titleCaseString.trim();
Give Us A Call Speak to our Team