Skip to content

replace

The replace filter is designed to replace all occurrences of a specific substring with another string. It is a versatile tool for modifying and transforming text content.

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 all occurrences of old_string with.
  • All Occurrences: Unlike replace_first, this filter replaces every instance of the old substring.
  • Output: Returns a new string with all replacements made.

Syntax

    {{ input_string | replace: old_string, new_string }}
Arguments

  • old_string: The substring you want to find and replace.
  • new_string: The string that will be substituted in place of the old_string.

Code Samples

Example 1: Replacing All Occurrences of a Word

    {% assign text = "The quick brown fox jumps over the lazy dog." %}
    {{ text | replace: "the", "a" }}
Output:
a quick brown fox jumps over a lazy dog.
Example 2: Replacing a Single Character

    {% assign word = "Hello" %}
    {{ word | replace: "l", "x" }}
Output:
Hexxo
Example 3: Replacing with an Empty String

    {% assign text = "This--is--a--string--with--extra--hyphens" %}
    {{ text | replace: "--", "" }}

Output:

This is a string with extra hyphens

Outliers and Special Cases

  • Empty Strings:
    • If old_string is empty, the filter does nothing and returns the original string.
    • If new_string is empty, all occurrences of old_string are 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 filter is a powerful string manipulation tool, allowing for bulk replacements within text.
  • It is case-sensitive. "The" and "the" would be considered distinct and replaced separately.
  • Be aware of the potential impact of replacing with an empty string, as it effectively deletes all occurrences of the old_string.
  • You can chain this filter with other string filters to perform more complex text transformations.