13

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.

H.Muster
  • 9,297
  • 1
  • 35
  • 46
OnionSandwich
  • 237
  • 1
  • 3
  • 9

1 Answers1

31

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.

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
  • Thanks Sergiu thats a great help. The original string will be a free format input field but I can get the user to use *** before the text they want to display. ALternatively, if the user started the output text on line 5 of the free format box, I could in theory create an array and output the 5th element onwards. Is this possible? I've tried using the carriage return as the split for each array element but cant seem to make that work. Any ideas? If not the above solution will work great. – OnionSandwich Sep 19 '12 at 09:58
  • It should work with `$string.split('\n')` in Velocity 1.7, although I'm not sure about previous versions. – Sergiu Dumitriu Sep 20 '12 at 01:47
  • Thanks Sergiu Dumitriu. I was able to use all public methods of String class after $myVariable=$myVariable.toString() – code chimp Jun 01 '15 at 13:29