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 ofold_stringwith.
- First Occurrence: Only the initial instance of
old_stringis replaced. - Output: Returns a new string with the replacement made.
Syntax
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:
Example 3: Substring Not Found Output:Outliers and Special Cases¶
- Empty Strings: If the
input_stringorold_stringis empty, the filter returns the originalinput_stringunchanged. - Substring Not Found: If the
old_stringis not found within theinput_string, the originalinput_stringis 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_firstfilter 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
replacefilter 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.