cssjspjstl

How to capitalize first letter with JSTL/CSS?


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!


Solution

  • 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>