String Filters
Alex Patton on Nov 3, 2021
String filters manipulate strings. You’ll recall that a string is a sequence of characters—letters, numerals, and special characters like punctuation—like your customer’s name, a sentence, or a product ID number. Thus, for the most part, we use string filters to manage the copy in our emails.
For example, you might use a string filter to change the case of a letter, remove unwanted whitespace, remove and/or replace words in sentences, add a line break, or add characters to the beginning or end of a string. String filters can also do things like replace characters in a string with URL-safe characters so your links work!
Let’s take a look at how the prepend filter helps us create more inviting copy to promote a product (in this case, nutritious chewy treat) by adding another string before the value, like this:
{{ product.product_name | prepend: "Be sure to reward your good boy with a " }}
Be sure to reward your good boy with a nutritious chewy treat!
Practice problem: string filters
Ready to test your string filter skills?
Add the new string “WOOF to our new products:” to the existing string “Your senior pet will say”. The final string should read:
Your senior pet will say WOOF to our new products:
The key that contains the woof value is pet.pet_sound. You must use the upcase filter (converts string value to all caps) and the append filter (adds a new string after the string value). Make sure to apply them in the right order!
Select the right Liquid code from the options below:
That’s not right; try again!
The right answer is A!
Let’s run the code:
Your senior pet will say {{ pet.pet_sound | upcase | append: "to our new products:" }}
Your senior pet will say WOOF to our new products:
Why don’t the other options work?
B) Applies the filters in the wrong order, capitalizing everything. The output would be “Your senior pet will say WOOF TO OUR NEW PRODUCTS.”
C) You must enclose the new string to be prepended in double quotes (all strings must be enclosed in double quotes).
D) You must reference the entire key: pet.pet_sound
Up Next: Intermediate Filters – Math Filters