'Truncate string in Liquid and remove last word

I'm using Liquid within a Jekyll-powered blog and currently trying to truncate various strings to a fixed size.

However, both built-in filters don't produce the output I'm trying to procude.

If I use truncate, I'm able to cut the string after a given number of characters:

{{ "Ground control to Major Tom." | truncate: 24 }} -> Ground control to Maj…

On the other hand, truncatewords allows me to shorten a string after a given number of words.

{{ "Ground control to Major Tom." | truncatewords: 4 }} -> Ground control to Major…

However, I want to truncate a string after x characters and then remove the last word in order to not have fragmented words left at the end of the string.

In the above example, my desired output after truncating 24 characters would be: Ground control to…

I tried to play around with the filter last, but didn't manage to find a suitable solution.

Any help is very appreciated!



Solution 1:[1]

I would just split the string by space, then sequentially append each word until the total length exceeds 24

{% assign string = "Ground control to Major Tom." | split: " " %}

{% assign shortstr = "" %}
{% for word in string %}
  {% assign tempstr = shortstr | append: word %}
  {% if tempstr.size <= 24 %}
    {% assign shorstr = tempstr | join: " " %}
  {% else %}
    {% break %}
  {% endif %}
{% endfor %}

I haven't tested it but it should be close if not ok

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andrea m.