0

I wanted to split a given string using jstl 1.2 eg:

Bean thesis.url contains "http:website1.com : http:website2.com"
which needs to be splited into
http:website1.com
http:website2.com

<c:set var="url">
  <c:out value="${thesis.url}" />
</c:set>  

<c:set var="offUrls" value="${fn:split(url,' : ')}" />
<c:forEach items="${offUrls}" var="link">
    <a href=" <c:out value='${link}' />" target="_blank">
        <c:out value="${link}" />
    </a>
</c:forEach>

But the output is not want I wanted which is
http
website1.com
http
website2.com

I tried another way, and its dint work either.
<c:set var="_split" value= " : "/>
<c:set var="offUrls" value="${fn:split(url,_split)}" />

user292049
  • 1,138
  • 1
  • 14
  • 20
  • possible duplicate of [How to correctly split strings in JSTL?](http://stackoverflow.com/questions/10304084/how-to-correctly-split-strings-in-jstl) – JB Nizet Sep 26 '12 at 14:47
  • @JBNizet: sorry for delay as I was trying to edit my post.and since I was just trying to familarising with adding a post in sov which i find it difficult. – user292049 Sep 26 '12 at 15:22

1 Answers1

4

fn:split will split your string on any of the delimiter characters, so in your case both space and :. The solution is to do a fn:replace first:

<c:set var="urls" value="http://website1.com : http://website2.com"/>
<c:set var="urls" value="${fn:replace(thesis.url, ' : ', '|')}"/>

Make sure to replace the separator with a character that is not present in your string, or else you will run into the same problem. Now you can use fn:split(urls, '|'), but it would be easier to use <c:forTokens/>:

<c:forTokens items="${urls}" delims="|" var="url">
  <a href="${url}">${url}</a>
</c:forTokens>

A better solution would be to simply do the work at the back end of your application and pass a list of strings to the front end.

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102