43

I want to replace a part of a string in Velocity Template Language with another string.

For Example:

#set($a = "Hello")
#set($b = "+")

I want to replace ll in Hello with ++. The output should be He++o

Please help me

Thanks Kishore

Dana
  • 2,619
  • 5
  • 31
  • 45
kishore
  • 431
  • 1
  • 4
  • 4

1 Answers1

79

By default you can use the methods of the Java String object:

#set( $a = "Hello" )
#set( $b = $a.replace("l", "+") )
${b}

will produce He++o and you can also use velocity variables as arguments to your method calls, e.g.:

#set( $a = "Hello" )
#set( $b = "+" )
#set( $c = $a.replace("l", ${b}) )
${c}
Mark McLaren
  • 11,470
  • 2
  • 48
  • 79
  • 1
    I just want to add a little note for future visitors: I had a very simple conversion in my velocity template from ö to oe, but it seemed like it was not working. Anyway, after a while I realised the character set of input was cp-1252 and jvm was working with utf-8 so the "ü" in the template was not the "ü" I was after.. – Koray Tugay Apr 14 '16 at 15:04
  • what is the purpose of the curly braces here? – fIwJlxSzApHEZIl Mar 15 '18 at 00:57
  • 1
    @anon58192932 Curly braces are for formal notion. In this specific example,they are not absolutely required. $b is an identical reference as ${b}. Link: [Apache](http://velocity.apache.org/engine/2.0/user-guide.html#formal-reference-notation) – Evadman Apr 18 '18 at 23:22