0
votes

I know how to split the string within a Controller or Domain class.

But i want to split the string inside the GSP.

My string will look like:

ASD25785-T

I want to be able to split this into 2 strings inside the GSP view.

String a = ASD25785
String b = T

Is it possible to do that inside the GSP?

2
It should just work, what have you tried? Also, if you have to do this in a view, a custom tag would probably be cleaner - tim_yates
Yes i have to do this in a view. I have no idea how to do a custom tag. - donguy76
Have you tried <% def (a,b) = 'ASD25785-T'.tokenize('-') %> - tim_yates

2 Answers

0
votes

How about something like this:

<%
   String[] tokens = "ASD25785-T".split("-")
   String b = tokens[0]
   String c = tokens[1]
%>

NB. use try catch because you may get ArrayOutofBoundException

0
votes

It depends if you have a predefind format or you want something generic.

Without try/catch and using the regex find method in String:

<%
String s="ASD25785-T"
String a,b 
s.find(/(.+)-(.+)/) { fullMatch, first, second -> [
    a=first
    b=second
}
%>

If you are certain that there will always be a match, then it is a cute one-liner:

<%
String s="ASD25785-T"
def (a,b) = s.find(/(.+)-(.+)/) { fullMatch, first, second -> [first,second]}
%>

Source: http://naleid.com/blog/2009/04/07/groovy-161-released-with-new-find-and-findall-regexp-methods-on-string

NB: However, if you want to use it in your view, you should create a tag. Grails taglibs are almost trivial to write, and much better to use in GSP code.

http://grails.github.io/grails-doc/2.4.x/ref/Command%20Line/create-tag-lib.html

http://grails.github.io/grails-doc/latest/guide/single.html#taglibs

Here's a string manipulation taglib

class StringsTaglib {
   def split = { attrs, body ->
       String input= attrs.input
       String regex= attrs.regex
       int position= attrs.index as Integer

       out << input.split(regex)[position]
    }
}

you could then use it like this:

a:<g:split input="ASD25785-T" regex="-" index="0"/>
b:<g:split input="ASD25785-T" regex="-" index="1"/>