cackoa
cackoa

Reputation: 125

Line break in JEXL String

I'm using JEXL in Java in standard way:

var script = new JexlBuilder().create().createScript(jexlScript);
var jexlContext = new MapContext(); 
var returnString = (String) script.execute(jexlContext));

Let's say that jexScript looks like:

var paramA = 'AAAA';
var paramB = 'BBBB';
var command = paramA + '\n' + paramB;
return command;

Output is:

AAAA\nBBBB

My question is: How to introduce new line char to properly format this text? Or any other way to get new line separation in String creating in Jexl.

Upvotes: 3

Views: 1009

Answers (1)

William Price
William Price

Reputation: 4102

I'm new to Apache JEXL, but I've found these ways:

1. Use multi-line strings

var paramA = 'AAAA';
var paramB = 'BBBB';
var command = `${paramA}
${paramB}`;
return command;

The literal newline in the multi-line string format (delimited with backticks) will be preserved. Use variable substitution to bring in your other variables.

2. Use the context to inject newline as a variable

In your Java code, populate the context:

var jexlContext = new MapContext(); 
jexlContext.set("newline", "\n");

Then use it in your script:

var paramA = 'AAAA';
var paramB = 'BBBB';
var command = paramA + newline + paramB;
return command;

3. Use Java-style Unicode escapes

This is a feature that existed but was undocumented prior to version 3.2 (JEXL-331). You can use a Java-style Unicode escape inside a string literal. The hexadecimal value of \n is 0x0a, so use:

var command = paramA + '\u000a' + paramB;

Upvotes: 3

Related Questions