flo bee
flo bee

Reputation: 840

Twig: How to get the last character in a string

I there,

I'm trying to find the last character for a string in twig. What I need to do is that if the string ends with s then I only add ' Zone and if the string doesn't have an s at the end I should add 's Zone.

E.g., "Charles's Zone" should become "Charles' Zone".

Thanks a lot

Upvotes: 2

Views: 7897

Answers (4)

Tom
Tom

Reputation: 81

From version 3, you can use slice filter like this:

{{ 'Charles\'s'|slice(0, -1) }}

{# outputs Charles' #}

or with shorthand notation:

{{ 'Charles\'s'[:-1] }}

{# outputs Charles' #}

Full Twig docs for slice: https://twig.symfony.com/doc/3.x/filters/slice.html

Upvotes: 0

Naman Joshi
Naman Joshi

Reputation: 46

using last


{{ [1, 2, 3, 4]|last }}

{# outputs 4 #}


{{ { a: 1, b: 2, c: 3, d: 4 }|last }}

{# outputs 4 #}


{{ '1234'|last }}

{# outputs 4 #}


Upvotes: 3

falinsky
falinsky

Reputation: 7428

{% set test_string = 'asdfs' %}
{% set test_string = test_string ~ (test_string|last == 's' ? "' " : "'s ") ~ "Zone" %}

Upvotes: 3

flo bee
flo bee

Reputation: 840

I figured a workaround:

{% set title = user_name ~ "\'s zone" %}
{% set replace_value_var= "s\'s zone" %}
{% set replace_with_value_var = "s\' zone"%}
{% set MyTitle =  title|replace({ (replace_value_var): replace_with_value_var })   %}

Upvotes: 0

Related Questions