Search code examples
twig

How to determine if last character is a dot and, if so, remove it


I have a webform with an open text-field in which anything can be entered. I need to display that input verbatim in a sentence, as part of a block of text.

What I want to do is to check if the last character of that text field input is a dot, and if so, remove it. What I found so far is that you can use "|last" to find the last character, and I found how to replace characters with nothing, effectively removing them.

But I can't figure out how to make it conditional, so that it only does the replace if the last character in the string is a dot, and also that it only replaces that specific dot without touching potential other dots in the string.


Solution

  • You are right the filter last will also return the last character of a string in twig. You can use this in any condition you want to, e.g.

    {% if foo|last == '.' %}
        Foo has a dot
    {% endif %}
    
    {% if bar|last == '.' %}
        Bar has a dot
    {% endif %}
    

    To remove the last character you can just use the filter slice

    {% if foo|last == '.' %}
        {{ foo[:-1] }}
    {% else %}
        {{ foo }}
    {% endif %}
    
    
    {% if bar|last == '.' %}
        {{ bar[:-1] }}
    {% else %}
        {{ bar }}
    {% endif %}
    

    demo


    You could also remove the if - endif as follows

    {{ foo|last == '.' ? foo[:-1] : foo }}
    {{ bar|last == '.' ? bar[:-1] : bar }}
    

    demo