Replace a Substring of a String in Velocity Template Language

56,391

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}
Share:
56,391
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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

  • Koray Tugay
    Koray Tugay about 8 years
    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..
  • fIwJlxSzApHEZIl
    fIwJlxSzApHEZIl over 6 years
    what is the purpose of the curly braces here?
  • Evadman
    Evadman about 6 years
    @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