I know there is a contains
keyword so I can use:
{% if some_string contains sub_string %}
<!-- do_something -->
{% ... %}
But how can I check if a string ends with a particular substring?
I've tried this but it won't work:
{% if some_string.endswith? sub_string %}
<!-- do_something -->
{% ... %}
As a workaround you could use the string slice
method
startIndex: some_string length - sub_string length
andstringLength: sub_string size
it's a bit clumpy in a liquid template but it would look like:
{% capture sub_string %}{{'subString'}}{% endcapture %}
{% capture some_string %}{{'some string with subString'}}{% endcapture %}
{% assign sub_string_size = sub_string | size %}
{% assign some_string_size = some_string | size %}
{% assign start_index = some_string_size | minus: sub_string_size %}
{% assign result = some_string | slice: start_index, sub_string_size %}
{% if result == sub_string %}
Found string at the end
{% else %}
Not found
{% endif %}
and if the some_string is empty or shorter than sub_string it works anyway because the slice result would be empty as well
With Jekyll, I ended up writing a small module-wrapper that adds a filter:
module Jekyll
module StringFilter
def endswith(text, query)
return text.end_with? query
end
end
end
Liquid::Template.register_filter(Jekyll::StringFilter)
I use it like this:
{% assign is_directory = page.url | endswith: "/" %}
We can use another solution with split
filter.
{%- assign filename = 'main.js' -%}
{%- assign check = filename | split:'js' -%}
{% if check.size == 1 and checkArray[0] != filename %}
Found 'js' at the end
{% else %}
Not found 'js' at the end
{% endif %}
Here we go ^^.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With