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?
Solved! Go to Solution.
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##
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"?
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##
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.
@SanfordWhiteman I'm looking forward to seeing the code. I presume it (in part) leverages this code? https://nation.marketo.com/t5/product-discussions/issue-splitting-string-with-regex-in-velocity/m-p/...
with a bit of conditional code set the delimiter to space if the passed in set of delimiters is empty?
It's the reconstituting the string with the original delimiters I'm excited to see. I can see some brute force ways to do it, but I imagine you've got a much more elegant approach.
Actually no, it isn’t based on a regex split (you could use a real Java Pattern + Matcher but we can't make one in Velocity). You'll see soon!
My anticipation grows!!