How can I split strings separated by "/" inside a jsp page using JSTL?
I have a string in this format: **
"23/11/2010"
*. Sometimes, the string could be like this: *
"1/1/2010"
*. I need to do something in order to split the string in three different substrings: *
"23", "11", "2010".
** This is because I need to put each one of them inside three different text fields, like these:
<input type="text" value="23">/
<input type="text" value="11">/
<input type="text" value="2010">
I could not find any working example yet.
Thanks in advance!
You can use the
fn:split()
function for this.Be sure that the date format is validated beforehand :) It would be easier if it was a
java.util.Date
, not ajava.lang.String
. You could then use<fmt:formatDate>
to format it to a reliable and fixed string format first. Otherwise you'd need to add checks on array length byfn:length()
and to prevent potential XSS attack holes byfn:escapeXml()
.Also important to note is that the function takes a regular expression as argument and not just a plain character sequence. So in case you'd like to split on characters which represent special characters in regex, then you'd need to escape them with backslashes. See also How to split a string in Java for general guidelines which also apply to
fn:split()
.It's worth noting for anyone else who finds this question in their searching (as I did) that JSTL has the useful tag
<c:forTokens>
. This will split the input string by a supplied delimiter and then iterate over the resultant collection of tokens.As demonstrated here, the following code:
Would result in:
Documentation: JSTL core Tag forTokens
Use the JSTL fn library. They have a split in there.