Reputation: 85516
I am coding a JSP/JSTL application. I would like to style a link with the first letter uppercase and the rest lowercase. For example "my LINK" would become "My Link".
I saw that in CSS I can do:
<a href="..." style="text-transform: capitalize">${linkName}</a>
Which works only when ${linkName} is all lower case, but doesn't work as I want when is uppercase for instance if it contains "MY LINK" will be still displayed all uppercase.
I was wondering what is the best way to solve this problem, for instance it could be to use JSTL to convert ${linkName} to lower case.
Anyone knows how to do that? Or any alternative way?
Thanks in advance!
Upvotes: 15
Views: 35358
Reputation: 1109222
If ${linkName}
is an instance of java.lang.String
and you're already on EL 2.2 or newer (a minimum of Tomcat 7 or newer), then you can simply directly invoke the String#toLowerCase()
method in EL.
<a href="..." style="text-transform: capitalize">${linkName.toLowerCase()}</a>
If you're not on EL 2.2 yet, then use JSTL functions fn:toLowerCase()
to lowercase a string.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<a href="..." style="text-transform: capitalize">${fn:toLowerCase(linkName)}</a>
Upvotes: 40
Reputation: 41
PFB the below code which would convert "i AM god" to "I Am God"
<c:forEach var="word" items="${fn:split(fn:toLowerCase(stringToBeConverted),' ')}">
<c:set var="formattedText" value="${formattedText} ${fn:toUpperCase(fn:substring(word,0,1))}${fn:toLowerCase(fn:substring(word,1,fn:length(word)))}" />
</c:forEach>
Upvotes: 2
Reputation: 6529
Apache Commons offers libraries to do lots of common useful tasks. WordUtils can help you here.
WordUtils.capitalizeFully("aaa BBB cCc");
Would output...
Aaa Bbb Ccc
Reference for WordUtils: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalizeFully%28java.lang.String%29
On my web app I added a wrapper for this in my TLD file...
<function>
<name>capitalize</name>
<function-class>org.apache.commons.lang3.text.WordUtils</function-class>
<function-signature>java.lang.String capitalizeFully(java.lang.String)</function-signature>
</function>
So now I can do this...
<p>Hello ${blah:capitalize(firstName)}</p>
I will leave you to read up on custom TLD files though, since other people explain it better.
Upvotes: 5
Reputation: 211
If you do not want to use CSS and only use JSTL, this solution have a bit extreme:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<a href="..." >
${fn:toUpperCase(fn:substring(linkName, 0, 1))}${fn:toLowerCase(fn:substring(linkName, 1,fn:length(linkName)))}
</a>
Upvotes: 21