Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions lib/solid/standard_filter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -705,25 +705,31 @@ defmodule Solid.StandardFilter do
"foo"
iex> Solid.StandardFilter.replace_last("foo", "f", "b")
"boo"
iex> Solid.StandardFilter.replace_last("Take my protein", nil, "#")
"Take my protein#"
"""
@spec replace_last(String.t(), String.t(), String.t()) :: String.t()
def replace_last(input, string, replacement) do
input = to_str(input)
string = to_str(string)
string_arg = to_str(string)
replacement = to_str(replacement)

case last_index(input, string) do
case last_index(input, string_arg) do
nil ->
input
if string_arg == "" do
input <> replacement
else
input
end

index ->
prefix = :binary.part(input, 0, index)

suffix =
:binary.part(
input,
index + byte_size(string),
byte_size(input) - (index + byte_size(string))
index + byte_size(string_arg),
byte_size(input) - (index + byte_size(string_arg))
)

prefix <> replacement <> suffix
Expand Down
1 change: 1 addition & 0 deletions test/solid/integration/scenarios/filter/input.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ base64
{{ "hello" | replace_last: "ll" }}
{{ "hello" | replace_last: "l", "p" }}
{{ "abab" | replace_last: "a", "c" }}
{{ "Take my protein" | replace_last: nosuchthing, "#" }}

default

Expand Down