Topic starter
25/10/2023 10:54 pm
Best way to split a string in thymeleaf with delimiter
Topic starter
25/10/2023 10:57 pm
In Thymeleaf, you can split a string into multiple parts using the #strings
utility object, which provides various string manipulation functions, including splitting a string. Here's how you can split a string using Thymeleaf:
Add the Thymeleaf xmlns:th
attribute to your HTML document to enable Thymeleaf expressions.
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <!-- Other HTML head content --> </head> <body> <!-- Your HTML body content --> </body> </html>
Use Thymeleaf expressions to split a string. Here's an example:
<div th:with="inputString='apple,banana,cherry'"> <!-- Split the inputString into an array using the ',' delimiter --> <ul th:with="stringArray=${#strings.arraySplit(inputString, ',')}"> <!-- Iterate over the array and display each part --> <li th:each="part : ${stringArray}" th:text="${part}"></li> </ul> </div>
In the code above:
- th:with is used to define a variable named inputString with the value 'apple,banana,cherry'
- th:with is used again to define a variable named stringArray by splitting the inputString using the #strings.arraySplit() function with the ',' delimiter.
- th:each is used to iterate over the elements in the stringArray, and th:text is used to display each part in an HTML list.
After processing, the HTML will display:
- apple - banana - cherry
You can replace 'apple,banana,cherry' with your own string and ',' with your desired delimiter to split the string as needed.
This post was modified 1 year ago 3 times by admin