Velocity script function to output text as Title Caps | Community
Skip to main content
Dan_Stevens_
New Participant
August 15, 2023
Solved

Velocity script function to output text as Title Caps

  • August 15, 2023
  • 1 reply
  • 3582 views

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.
Best answer by Crystal_Pacheco

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##

1 reply

Dan_Stevens_
New Participant
August 15, 2023

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"?

Crystal_Pacheco
Crystal_PachecoAccepted solution
New Participant
August 15, 2023

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##

SanfordWhiteman
New Participant
August 16, 2023

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.