Fleshgrinder
Fleshgrinder

Reputation: 16253

Apache Velocity to replace backslash with two backslashes

I want to replace a single backslash with two backslashes within an Apache Velocity template in PhpStorm. Sadly, nothing seems to work. Here are a few attempts of mine, none of which worked.

${VAR.replace("\\", "\\\\")}
${VAR.replace("\\", "\\\\\\")}
${VAR.replace("\\", "\\\\\\\\")}
${VAR.replace("\\\\", "\\\\\\\\")}

I tried various other combinations, including ${esc.b} and ${esc.backslash} which are provided by Velocity. Absolutely nothing works.

I want to transform the namespace into a quoted string within a PHP file, that is why I need two backslashes in the output instead of one.

Any ideas?

Upvotes: 0

Views: 1287

Answers (1)

LazyOne
LazyOne

Reputation: 165118

  1. Use replaceAll as replace works with single characters only.
  2. Do it using #set instruction

Example:

#set($newVar = $namespace.replaceAll("\\", "\\\\"))
$newVar

Example input data for namespace variable: qwe\asd\asd

Result:

qwe\\asd\\asd

Upvotes: 1

Related Questions