replace_last¶
The replace_last filter is designed to replace the last occurrence of a specific substring with another string. It functions similarly to the replace filter, but only targets the final instance of the search substring.
Functionality
- Strings: Takes a string as input.
- Search and Replace: Requires two string arguments:
old_string: The substring to search for within the input string.new_string: The string to replace the last occurrence ofold_stringwith.
- Last Occurrence: Only the final instance of
old_stringis replaced. - Output: Returns a new string with the replacement made.
Syntax
Arguments
- old_string: The substring you want to find and replace in its last occurrence.
- new_string: The string that will be substituted in place of the last found
old_string.
Code Samples
Example 1: Replacing the Last Word
{% assign sentence = "This is a test test sentence." %}
{{ sentence | replace_last: "test", "example" }}
Output:
Example 2: Replacing the Last CharacterOutput:
Example 3: Substring Not FoundOutput:
Outliers and Special Cases¶
- Empty Strings:
- If
old_stringis empty, the filter returns the originalinput_stringunchanged. - If
new_stringis empty, the last occurrence ofold_stringis effectively removed.
- If
- Substring Not Found: If
old_stringis not found within theinput_string, the original string is returned unchanged. - Non-String Input: If the input or arguments are not strings, the filter might attempt to convert them to strings or return an error, depending on how Experience Builder handles type conversions.
Key Points¶
- The
replace_lastfilter provides precise control over string replacement by targeting only the final instance of a substring. - It is case-sensitive. "Test" and "test" are treated as different strings.
- Consider using the
replacefilter if you need to replace all occurrences of a substring. - Combine this filter with other string manipulation filters to achieve more complex transformations.
- Remember that the original string remains unmodified; a new string with the replacement is returned.