Output part of a string in velocity

user1680260 picture user1680260 · Sep 18, 2012 · Viewed 24.5k times · Source

apologies if I waffle or talk a bit of jibberish but I'm new to velocity, and these forums!

I need to check the contents of a string for a certain character and output the second part of the text if it appears. For example:

set ($string = "This is a long string *** but I only want to output this on my email").

I want to output all text after the 3 Asterisks. I've scoured the forums but cant quite find anything that helps me completely.

Answer

Sergiu Dumitriu picture Sergiu Dumitriu · Sep 19, 2012

Velocity is just a façade for real Java objects, so you have access to all the public methods of the String class, including indexOf and substring. So try something like:

#set ($string = "This is a long string *** but I only want to output this on my email")
#set ($index = $string.indexOf('***'))
#set ($index = $index + 3)
#set ($end = $string.substring($index))

If you have more control over what objects you put in the context, you could add an instance of StringUtils as a helper tool, and then use substringAfter directly.