Extract first word from string

New Member
16 0 0

I am trying to extract the first word from a string.  Can anyone help?

My string is August - Holiday and I want remove a section of the string and then append it to another HTML element. How can I do this?

This would be the intended result:

<span>August</span>
<span>Holiday</span>

I can't seem to find anything in the documentation.

Thanks

0 Likes
Shopify Partner
23 0 8

Hi Tomato,

You can achieve this results by jQuery detach/append script.

Thanks,
PSDCenter

Support@PSDCenter.com || www.PSDCenter.com || Themes.PSDCenter.com
0 Likes
New Member
16 0 0

I want to avoid using JavaScript if at all possible. There's already significant JS overhead. 

Thanks anyway.

0 Likes
Shopify Expert
9807 92 1561

Hey Tomato,

Try something like this:

{% assign foo = 'August - Holiday' %}

{% assign stringSplit = foo | split:'-' %}

{% for stringPart in stringSplit %}
  <span>{{ part | strip }}</span>
{% endfor %}

The first couple of lines you'd want to adapt to whatever your usage will be but the split filter should do what you need.

What I'm not 100% sure on is where you're pulling the word exotic from.

Not something you need to use JavaScript for.

★ Winning Partner of the Build a Business competition. ★ http://freakdesign.com.au
1 Like
New Member
16 0 0

Thanks @Jason. This is what I did in the end:

 

{% if article.tags contains 'box' %}
{% comment %}If the blog post has a tag 'box' {% endcomment %}

{% assign box_title = {{article.title}} %}
{% comment %}Assign article blog title as box title {% endcomment %}
{% assign stringSplit = box_title | split:'-' %}
{% comment %} Split box title string {% endcomment %}

  {% for stringPart in stringSplit %}
  {% comment %} Loop through string parts {% endcomment %}

      {%if forloop.first == true %}

      {% comment %} First item in loop is different {% endcomment %}

      <span class="db f6 white fw1 tc ttu tracked mv1">{{ stringPart | strip }}</span>

      {% else %}

      <span class="db lh-heading ma0 tc f1-m fw7 white">{{ stringPart | strip }}</span>

      {% endif %}

  {% endfor %}

  {% else %}

Not a box.
{% endif %}

 

0 Likes
New Member
1 0 0

This is a very old thread but a single line solution is to use the truncatewords filter to get just the first word.

ref: https://shopify.github.io/liquid/filters/truncatewords/

 

{{ "Ground control to Major Tom." | truncatewords: 1, "" }}
0 Likes