简体   繁体   中英

How to build URL for string and add to list in groovy

I have a list like below ticketList and need a ResultList as below with a hyperlink attached

ticketList = [JR8908,JR7676,JR7687,JR8798]

I want the result ResultList: [ JR8908 , JR7676 , JR7687 , JR8798 ]

Hyperlink would be - http://localhost:8080/browse/ticketID

End point will change for each ticket, it will be ticket ID

Tried Code:

ticketList = ["JR8908","JR7676","JR7687","JR8798"]
finalList = [] 

ticketList.eachWithIndex { ticket, index ->
            println ticket
    replacedstring = ticket.replaceAll("$ticket", "<a href='http://localhost:8080/browse/$ticket'>$ticket</a>")
        finalList.add(replacedstring)
}
        println finalList

finalist result is below:

[<a href='http://localhost:8080/browse/JR8908'>JR8908</a>, <a href='http://localhost:8080/browse/JR7676'>JR7676</a>, <a href='http://localhost:8080/browse/JR7687'>JR7687</a>, <a href='http://localhost:8080/browse/JR8798'>JR8798</a>]

But,I want it like: [ JR8908 , JR7676 , JR7687 , JR8798 ]

Use collect with String interpolation:

def ticketList = ["JR8908","JR7676","JR7687","JR8798"]

def finalList = ticketList.collect{ "<a href='http://localhost:8080/browse/$it'>$it</a>" }

assert finalList.toString() == '[<a href='http://localhost:8080/browse/JR8908'>JR8908</a>, <a href='http://localhost:8080/browse/JR7676'>JR7676</a>, <a href='http://localhost:8080/browse/JR7687'>JR7687</a>, <a href='http://localhost:8080/browse/JR8798'>JR8798</a>]' 

It looks like you want the output to be strings but your code is printing a list. You will have to iterate over the list:

finalList.each { println it }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM