Skip to content

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 of old_string with.
  • Last Occurrence: Only the final instance of old_string is replaced.
  • Output: Returns a new string with the replacement made.

Syntax

    {{ input_string | replace_last: old_string, new_string }}

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:

This is a test example sentence.
Example 2: Replacing the Last Character
    {% assign punctuation = "Hello!!!" %}
    {{ punctuation | replace_last: "!", "?" }}

Output:

Hello??
Example 3: Substring Not Found

    {% assign text = "This string does not contain 'xyz'" %}
    {{ text | replace_last: "xyz", "abc" }}

Output:

This string does not contain 'xyz' (No change)

Outliers and Special Cases

  • Empty Strings:
    • If old_string is empty, the filter returns the original input_string unchanged.
    • If new_string is empty, the last occurrence of old_string is effectively removed.
  • Substring Not Found: If old_string is not found within the input_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_last filter 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 replace filter 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.