Skip to main content
Dan_Stevens_
Level 10
Aug 15, 2023 5:12 PM UTC
Solved

Velocity script function to output text as Title Caps

Does a function exist for Velocity that will transform a string of text to title caps format?  For example, if first name is in all-caps, how can output that as Xxxxx?

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Crystal_Pacheco
Crystal_PachecoAccepted solution
Level 4
Aug 15, 2023 7:14 PM UTC

Hi @dan_stevens_ ,
Unfortunately, there isn't a built-in method in velocity for capitalizing each word in a string. So we manually achieve title casing by splitting the input text into words, capitalizing the first letter of each word, and converting the rest of the letters to lowercase.

In this example, the input text "take me out to the ballgame" will be converted to "Take Me Out To The Ballgame" using Velocity script.

#set($inputText = "take me out to the ballgame") #set($words = $inputText.split(" ")) #foreach($word in $words) #set($capitalizedWord = $word.substring(0,1).toUpperCase() + $word.substring(1).toLowerCase()) $capitalizedWord## #end


Ending the output with a ## to remove any extra spaces
$capitalizedWord##

6 replies

Dan_Stevens_
Level 10
Aug 15, 2023 6:16 PM UTC

I actually found the solution that @sanfordwhiteman provided here: https://nation.marketo.com/t5/product-discussions/velocity-scripting-make-lowercase/td-p/26358

 

But what if there are more than one name in the firstname field, e.g., "JOHN MICHAEL"?

Translate
Crystal_Pacheco
Crystal_PachecoAccepted solution
Level 4
Aug 15, 2023 7:14 PM UTC

Hi @dan_stevens_ ,
Unfortunately, there isn't a built-in method in velocity for capitalizing each word in a string. So we manually achieve title casing by splitting the input text into words, capitalizing the first letter of each word, and converting the rest of the letters to lowercase.

In this example, the input text "take me out to the ballgame" will be converted to "Take Me Out To The Ballgame" using Velocity script.

#set($inputText = "take me out to the ballgame") #set($words = $inputText.split(" ")) #foreach($word in $words) #set($capitalizedWord = $word.substring(0,1).toUpperCase() + $word.substring(1).toLowerCase()) $capitalizedWord## #end


Ending the output with a ## to remove any extra spaces
$capitalizedWord##

Translate
SanfordWhiteman
User Group Leader
User Group Leader
Aug 16, 2023 12:02 AM UTC

This’ll get you somewhere, but it doesn't cover all the expectations of title case. Remember, whitespace isn't the only word break: people typically want hyphens, slashes, and/or periods as well. Otherwise Crazy-Beautiful, Inc. becomes “Crazy-beautiful, Inc.”.

 

There's a Apache Commons WordUtils function, capitalizeFully, that I'll translate to Velocity and post on the Nation blog.

Translate