Skip to content

replace_first

The replace_first filter is designed to replace the first occurrence of a specific substring with another string.

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

Syntax

    {{ input_string | replace_first: old_string, new_string }}

Arguments

  • old_string: The substring to find and replace.
  • new_string: The replacement string to insert in place of the first occurrence of old_string.

Code Samples

Example 1: Replacing a Word

    {% assign sentence = "This is a test test sentence." %}   
    {{ sentence | replace_first: "test", "sample" }}
Output:
This is a sample test sentence.
Example 2: Replacing a Single Character

    {% assign word = "Hello" %}

    {{ word | replace_first: "e", "a" }}

Output:

Hallo
Example 3: Substring Not Found

    {% assign text = "This string does not contain 'xyz'" %}

    {{ text | replace_first: "xyz", "abc" }}
Output:
This string does not contain 'xyz' (No change)

Outliers and Special Cases

  • Empty Strings: If the input_string or old_string is empty, the filter returns the original input_string unchanged.
  • Substring Not Found: If the old_string is not found within the input_string, the original input_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_first filter is precise in targeting only the first occurrence of a substring.
  • It is case-sensitive, meaning "Test" and "test" are treated as different strings.
  • Consider using the replace filter if you need to replace all occurrences of a substring.
  • You can combine this filter with other string manipulation filters to achieve more complex transformations.
  • Remember that the original string is not modified; a new string with the replacement is returned.