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
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
well actually
  • 11,810
  • 19
  • 52
  • 70
  • 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 finicky – mrk Jul 27 '11 at 00:20
  • no, that doesn't help things. good idea though. – well actually Jul 27 '11 at 00:22
  • 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] tag – Sanghyun Lee Jul 27 '11 at 05:26
  • 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. – mrk Jul 27 '11 at 15:40
  • 1
    @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. – BalusC Jul 27 '11 at 15:48

1 Answers1

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;
}
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555