Search code examples
stringthymeleaf

thymeleaf multi string replace


I want to do a string replace on multiple keywords:

<td th:text="${#strings.arrayReplace(strLocation,['Latitude: ', 'Longitude: '], ['',''])}"></td>

Solution

  • Short Answer

    I think you want multipleReplace not arrayReplace. But just in case, I have shown both methods below.


    Longer Answer

    Using arrayReplace:

    You can see the method signature of the arrayReplace method here:

    public String[] arrayReplace(Object[] target, String before, String after)

    So, an example of how to use that is as follows:

    Map<String, Object> model = new HashMap<>();
    // arrayReplace example:
    String[] targetArray = {"Volvo", "BMW", "Ford"};
    model.put("targetArray", targetArray);
    model.put("before", "Ford");
    model.put("after", "Mazda");
    

    And the related Thymeleaf:

    #strings.arrayReplace(targetArray, before, after)
    

    This replaces all occurrences of Ford with Mazda in the array.

    A demo (I wrap the array output in arrayJoin, so you can actually see the data in your HTML:

    <div th:text="${#strings.arrayJoin(targetArray, ', ')}"></div>
    <br>
    <div th:text="${#strings.arrayJoin(#strings.arrayReplace(targetArray, before, after), ', ')}"></div>
    

    Using multipleReplace:

    However, I don't think this is what you want. I think you want to take a string such as this:

    Latitude: 1.23456, Longitude: 2.34567
    

    and convert it to this:

    1.23456, 2.34567
    

    To do that, you can use multipleReplace:

    The Java test data:

    // multipleReplace example:
    String targetString = "Latitude: 1.23456, Longitude: 2.34567";
    String[] beforeArray = {"Latitude: ", "Longitude: "};
    String[] afterArray = {"", ""};
    model.put("targetString", targetString);
    model.put("beforeArray", beforeArray);
    model.put("afterArray", afterArray);
    

    The Thymeleaf:

    <!-- multipleReplace -->
    <div th:text="${targetString}"></div>
    <br>
    <div th:text="${#strings.multipleReplace(targetString, beforeArray, afterArray)}"></div>
    

    The resulting HTML, showing the "before" and "after" strings:

    <div>Latitude: 1.23456, Longitude: 2.34567</div>
    <br>
    <div>1.23456, 2.34567</div>