Trim string to x characters in Velocity | Community
Skip to main content
Level 9
April 1, 2020
Solved

Trim string to x characters in Velocity

  • April 1, 2020
  • 1 reply
  • 13685 views

Hi all

 

Trying to do something which should be pretty straightforward - struggling! I'm trying to take a 18 character ID and take the first 15 characters from the left. 

 

I've looked up the string documentation and found $String.chop(), but using things like:

 

#set($id = "001jdhvie9584nvjdk") #set($id = $id.chop(3)) ###or### #set($id = $String.chop($id, 3) $id

 

Gives me simply $id as output. Trying logical methods such as "left" or .get(0,15) doesn't work either.

 

What am I missing? Thanks!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by SanfordWhiteman

 

 

#set( $first15ViaTruncate = $display.truncate($id,15,"") )

 

 

 

If you check first that you have at least 15 chars, you can use

 

#set( $first15ViaSubstring = $id.substring(0,15) )

 

 

If you do not check first, substring will throw a fatal error on unexpectedly short input. The Velocity tools are purposely more forgiving.

 

Don't know what String.chop you're referring to.

 

1 reply

SanfordWhiteman
SanfordWhitemanAccepted solution
Level 10
April 1, 2020

 

 

#set( $first15ViaTruncate = $display.truncate($id,15,"") )

 

 

 

If you check first that you have at least 15 chars, you can use

 

#set( $first15ViaSubstring = $id.substring(0,15) )

 

 

If you do not check first, substring will throw a fatal error on unexpectedly short input. The Velocity tools are purposely more forgiving.

 

Don't know what String.chop you're referring to.

 

Level 9
April 2, 2020

Thanks Sanford! Works like a charm.

 

So I got chop from here: https://velocity.apache.org/engine/1.7/apidocs/org/apache/velocity/util/StringUtils.html. To be honest when I'm looking for methods I don't know I.....don't know where I should be looking! What is your master reference for methods? I feel that some Velocity code is available in Marketo and some isn't, but I don't know of a reference that exists. 

SanfordWhiteman
Level 10
April 2, 2020

StringUtils is an internal class, not a Velocity Tool. It isn't exposed in vanilla Velocity (you could export it into the context if you were in control of the Velocity engine, but for obvious security reasons we are not!).

 

The Generic Tools are the ones at https://velocity.apache.org/tools/devel/generic.html#tools, although not all are available within Marketo, for example Render, Class, Context, and Resource are not present and Xml is broken.