1

How to convert 1st letter of each word to uppercase. Is there a way to achieve this?

Here is my visualforce page:

<apex:pageblockTable value="{!myWrapperList}" var="mw">
  <apex:column value="{!mw.name}"/>
  <apex:column value="{!mw.status}"/>
</apex:pageBlockTable>

Output is something like this:

eric     active
john     inactive
joe      active

Desired output should be first character upper case:

Eric     Active
John     Inactive
Joe      Active
1
  • Any luck on this one?
    – Adrian Larson
    Jun 23, 2016 at 23:40

2 Answers 2

3

It should be possible to manipulate a single value using just merge syntax:

<apex:column value="{!UPPER(LEFT(mw.name, 1)) & MID(mw.name, 2, LEN(mw.name))}" />

Here is a more elegant approach if you wish to use Apex:

static String capitalizeWords(String input)
{
    String output = '';
    Matcher m = Pattern.compile('(\\w+|\\W+)').matcher(input);
    while (m.find()) output += m.group().capitalize();
    return output;
}

The above can handle whitespace characters outside of just a single space, and doesn't need to do nearly as much string manipulation.

While it is slightly slower, this approach also works for edge cases like having a line break character right before a word. Consider:

String input = 'alice and bob\ncarrie and denise\nelbert and frank';

This Approach

Alice And Bob
Carrie And Denise
Elbert And Frank

Prior Approach

Alice And Bob
carrie And Denise
elbert And Frank

3
  • why can't be access this method from vfp i have tried doing something like this <apex:column value="{!capitalizeWords(mw.status)}"/> then getting this error Unknown function capitalizeWords. Check spelling i have this method as static in the controller class
    – Nick
    Jun 24, 2016 at 21:22
  • You can't call Apex methods in merge fields, other than get/set property methods. See my top section on how to use a merge field...
    – Adrian Larson
    Jun 24, 2016 at 21:24
  • For title casing, you can use @AdrianLarson solution above, but first convert the input to lowercase via input.toLowerCase() in order to handle input with all caps. Feb 21, 2022 at 3:00
0

As salesforce does not provide method for this, you can try below option.

Referring to below link solution given by @brovasi,

capitalizing 1st character of each word in a string

String rep_name = 'david john mitch doe';
List<String> elems = rep_name.split(' ');
rep_name = '';
for (String x : elems)
{
    rep_name += x.substring(0,1).toUpperCase()+x.substring(1,x.length()) + ' ';
}
System.debug('>>>'+rep_name);

Hope this helps :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .