How to concatenate Strings in EL? [duplicate]
Asked Answered
M

1

1

Apparently, you cannot use the normal + operator to append strings in jsp...at least its not working for me. Is there a way to do it? Fragment of my code that is relevant...

${fn:length(example.name) > 15 ? fn:substring(example.name,0,14) + '...' : example.name} // does not work because of + operator
Madea answered 27/7, 2011 at 0:8 Comment(5)
Are you sure you don't need parens around fn:substring(example.name,0,14) + '...'? I've always found Java's ternary operator to be finickySusi
no, that doesn't help things. good idea though.Madea
I think it would be better to move the logic into the example's getName() function. And I wonder why this thread has the [javascript] tag? I think an [el] tag should be here instead of the [javascript] tagGlasshouse
I second Sangdol's idea, but with a slight adjustment...looks like you are truncating, perhaps for only UI purposes. How about adding a getNameForUI() call? I've followed a naming convention like that (...forUI()) before and it helps if only a few data points have to be slightly altered for appearance sake in a UI. This idea breaks down though if lots of different datapoints have to be truncated.Susi
@mrk: that "finicky" behaviour only occurs whenever you've multiple of them in a single EL expression such as in ${cond1 ? .. : cond2 ? ... : ...}. The Apache EL parser (which is the most widely used one) has indeed quirks with this. There's in this particular case however no means of multiple conditional expressions.Cyclist
C
3

EL does not know a string concatenation operator. Instead, you would just inline multiple EL expressions together. The + operator is in EL exclusively a sum operator for numbers.

Here's one of the ways how you could do it:

<c:set var="tooLong" value="${fn:length(example.name) > 15}" />
${tooLong ? fn:substring(example.name,0,14) : example.name}${tooLong ? '...' : ''}

Another way is to use an EL function for this wherein you can handle this using pure Java. For an example, see the "EL functions" chapter near the bottom of my answer in Hidden features of JSP/Servlet. You would like to end up as something like:

${util:ellipsis(example.name, 15)}

with

public static String ellipsis(String text, int maxLength) {
    return (text.length() > maxLength) ? text.substring(0, maxLength - 1) + "..." : text;
}
Cyclist answered 27/7, 2011 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.