What is the use of various replace_xxxx functions in the String module

I wonder what is the use of these functions

  • replace_leading/3
  • replace_prefix/3
  • replace_suffix/3
  • replace_trailing/3

in the string module. I tried to understand from the examples in their documentation. I compared the results with the simple replace/3 and I didn’t notice any difference.

So what is their use case? Why should I use them over simple replace?

1 Like

The difference is, for example:

iex> String.replace_prefix("hello hello world hello world", "hello ", "foo ")
"foo hello world hello world"
iex> String.replace_leading("hello hello world hello world", "hello ", "foo ")
"foo foo world hello world"
iex> String.replace("hello hello world hello world", "hello ", "foo ")
"foo foo world foo world"

The case for functions working at the end of the string is analogous.