Replacing the last occurence of a substring by a different string

Hey Sven, Sam,

First of all: very nice presentations in the Ghelamco for the both of you: learned a few new tips & tricks thanks to you guys :-).

A question: I once read a discussion about how you can replace the last occurence of a string by a different string in liquid (I think it was about person A, B, C that was transformed to A, B and C).

Problem is that I can’t find this discussion any more. Any help?

Thanks!

Hi Bart

I couldn’t find it either but it reminds me of the following but I am wondering if this is what you need?

{% stripnewlines %}
{% for person in people.directors %}
  {% unless forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endunless %}
  {{ person.name }}
{% endfor %}
{% endstripnewlines %}

Kind regards
Sam

PS: thanks for the compliment.

Hi Sam,

Not exactly but it gave me the inspiration to construct a similar version, so thanks. Here’s my code (which is not as elegant as yours but it works :-)):

{% comment %}haal de namen van alle vennootschappen uit de parameters{% endcomment %}
{% assign str_VGD_Vennootschappen_Namen = period.reconciliations.Parameters.results.VGD_Vennootschappen_Namen | strip %}
{% assign arr_VGD_Vennootschappen_Namen = str_VGD_Vennootschappen_Namen | split: ‘|’ %}
{% assign int_XthCommaToReplace = arr_VGD_Vennootschappen_Namen.size | minus: 1 %}

{% comment %}vervang de ‘|’ door ', ’ (behalve de laatste door ’ en '{% endcomment %}
{% for vennootschap in arr_VGD_Vennootschappen_Namen %}
{% assign counter = counter | plus:1 %}
{% if counter == int_XthCommaToReplace %}
{% assign str_Vennootschappen_Correct = str_Vennootschappen_Correct | append: vennootschap | append: ’ en ’ %}
{% else %}
{% assign str_Vennootschappen_Correct = str_Vennootschappen_Correct | append: vennootschap | append: ', ’ %}
{% endif %}
{% endfor %}

{% assign str_Vennootschappen_Correct_Length = str_Vennootschappen_Correct.size | minus: 2 %}
{% assign str_Vennootschappen_Correct = str_Vennootschappen_Correct | slice: 0, str_Vennootschappen_Correct_Length %}

{{str_Vennootschappen_Correct}}

By the way, would be great if I could implement this logic in a custom function and call this every time I need this (which, if I remember correctly, will be a new feature in the near future).