Shantelle
Shantelle

Reputation: 11

Capitalize the first letter of each word, with the exception of one word

I'm using {% capture %} in Liquid to capitalize the first letter of each word and this is working as expected. The issue I'm facing is if that sentence contains 'And', I need 'And' only to remain lowercase.

I've tried just being quite simple with it by using 'replace' on the final output, but no luck.

Example - I'm capturing 'firstname' on a form - but the user has put in theirs and their partners name all in a mix of up/down case 'jack-ANd-SaLly'

I use the below, which gives me 'Jack And Sally'

{% assign words = contact.data.firstname | replace: '-', ' ' %}
{% assign words = words | split: ' ' %}
{% capture f_name %}
  {% for word in words %}
    {{ word | capitalize }}
  {% endfor %}{% endcapture %}
{{ f_name }}

I then try this at the end - but I still get 'Jack And Sally'

{{ f_name | replace: ' And ', ' and ' }}

Upvotes: 0

Views: 409

Answers (2)

Alice Girard
Alice Girard

Reputation: 2183

Something like this?

{% assign words = contact.data.firstname split: '-' %}
{% capture f_name %}
  {% for word in words %}
    {{ word | capitalize | replace:'And', 'and' | append: ' ' }}
  {% endfor %}
{% endcapture %}
{{ f_name }}

Upvotes: 0

Fabio Filippi
Fabio Filippi

Reputation: 1965

The problem is somehow in the spaces. If you remove them it works, but I understand that could lead to other problems. Another solution is to not capitalize the unwanted word in the first place

{% layout none %}
{% assign words = "jack-and-sally" | replace: '-', ' ' %}
{% assign exceptions = 'and,or' | split: ',' %}
{% assign words = words | split: ' ' %}
{% capture f_name %}
    {% for word in words %}
        {% if exceptions contains word %}
            {{ word }}
        {% else %}
            {{ word | capitalize }}
        {% endif %}
    {% endfor %}
{% endcapture %}
{{ f_name }}

Upvotes: 0

Related Questions