Re: How to remove content within round brackets in a string in Velocity?

Cristina_Leonet
Level 2

How to remove content within round brackets in a string in Velocity?

We want to have FirstName LastName (Abbr.) displayed as FirstName LastName.

I'm trying with regex but is not working, I'm new in velocity, and I would like kindly ask what's wrong in the script:

I tried this version:

#set ($string = ${lead.Account_Owner__c})
#set ($var1 = $string.replace("/\(\w+\)/", ""))
This is the Account Owner Without Abbreviation: $var1

This is not removing anything.

-----

This the other version I tried:

#set ($string = ${lead.Account_Owner__c})
#set ($var1 = $string.replace(/\(\w+\)/, ""))
This is the Account Owner Without Abbreviation: $var1

This script gives an error.

Thanks in advance!

Cheers,

Cristina

#velocity my token#velocity script #velocity error #velocity scripting

4 REPLIES 4
SanfordWhiteman
Level 10 - Community Moderator

Re: How to remove content within round brackets in a string in Velocity?

Please highlight your code using the Syntax Highlighter (use Java as it's closest to VTL) then we'll continue.

Cristina_Leonet
Level 2

Re: How to remove content within round brackets in a string in Velocity?

Hello Sanford! Thanks a lot for your reply!

Do you think we can continue now?


#set ($string = ${lead.Account_Owner__c})#set ($var1 = $string.replace("/\(\w+\)/", ""))This is the Account Owner Without Abbreviation: $var1

#set ($string = ${lead.Account_Owner__c})#set ($var1 = $string.replace(/\(\w+\)/, ""))This is the Account Owner Without Abbreviation: $var1
SanfordWhiteman
Level 10 - Community Moderator

Re: How to remove content within round brackets in a string in Velocity?

You're overly restricting the characters in parens. You want to strip anything in parentheses that's anchored at the end of the string, including leading and trailing whitespace.

#set ($accountOwner = $lead.Account_Owner__c)
#set ($accountOwnerSimple = $accountOwner.replaceAll("\s*\(.*\)\s*$", ""))
This is the Account Owner Without Abbreviation: $accountOwnerSimple

Also:

  • always use informative variable names so your code is maintainable
  • don't use curly braces (formal references) except in output
Cristina_Leonet
Level 2

Re: How to remove content within round brackets in a string in Velocity?

Thank you so much for guides! I need to do more training on velocity script, and I'm happy to learn from the bests!