sergut
sergut

Reputation: 299

Get last two characters of a string in Liquid

I want to extract the last two characters of a string using Liquid, but I have not found a good way.

My best attempt so far has been to assume that the string is a big number (which is a valid assumption in my specific use case) and use "modulo 100 on the number", i.e. I am using

{{{some_object.${some_numeric_property} | modulo:100 }}

There are two problems with this approach:

a) it only works with numbers, obviously.

b) it does not work well with numbers that end in 00--09, e.g. if the string is '76368408', the result of the modulo operation is '8', not '08'.

So I guess this question is twofold: i. Ideally, is there a generic way to split the last two characters of a string in Liquid? ii. If not, is there a way to split the last two digits of a last number without removing a trailing zero?

Upvotes: 1

Views: 3601

Answers (2)

sergut
sergut

Reputation: 299

For strings: slice with negative indexes.

{{ some_object.${some_property} | slice: -2,2 }}

For numbers: first convert to string, then slice with negative indexes.

{{ some_object.${some_numeric_property} | append:"" | slice: -2,2 }} 

(Thanks to Alice Girard for the main idea.)

Upvotes: 1

Karim Tarek
Karim Tarek

Reputation: 907

The code probably could be improved, however this should do it:

{% liquid 
  assign last_two_chars = "" 
  assign split_word = "last two chars" | split: ""
  
  for char in split_word 
    assign char_before_last_index = forloop.length | minus: 1  
    if forloop.index == char_before_last_index 
      assign last_two_chars = last_two_chars | append: char 
    endif 
    if forloop.last 
      assign last_two_chars = last_two_chars | append: char 
    endif 
  endfor 
%}

last_two_chars: {{ last_two_chars }}

Upvotes: 0

Related Questions