String.replace
replace
, go back to String module for more information.
Specs
Returns a new string created by replacing occurrences of pattern
in
subject
with replacement
.
The subject
is always a string.
The pattern
may be a string, a list of strings, a regular expression, or a
compiled pattern.
The replacement
may be a string or a function that receives the matched
pattern and must return the replacement as a string or iodata.
By default it replaces all occurrences but this behaviour can be controlled
through the :global
option; see the "Options" section below.
Options
:global
- (boolean) iftrue
, all occurrences ofpattern
are replaced withreplacement
, otherwise only the first occurrence is replaced. Defaults totrue
Examples
iex> String.replace("a,b,c", ",", "-")
"a-b-c"
iex> String.replace("a,b,c", ",", "-", global: false)
"a-b,c"
The pattern may also be a list of strings and the replacement may also be a function that receives the matches:
iex> String.replace("a,b,c", ["a", "c"], fn <<char>> -> <<char + 1>> end)
"b,b,d"
When the pattern is a regular expression, one can give \N
or
\g{N}
in the replacement
string to access a specific capture in the
regular expression:
iex> String.replace("a,b,c", ~r/,(.)/, ",\\1\\g{1}")
"a,bb,cc"
Note that we had to escape the backslash escape character (i.e., we used \\N
instead of just \N
to escape the backslash; same thing for \\g{N}
). By
giving \0
, one can inject the whole match in the replacement string.
A compiled pattern can also be given:
iex> pattern = :binary.compile_pattern(",")
iex> String.replace("a,b,c", pattern, "[]")
"a[]b[]c"
When an empty string is provided as a pattern
, the function will treat it as
an implicit empty string between each grapheme and the string will be
interspersed. If an empty string is provided as replacement
the subject
will be returned:
iex> String.replace("ELIXIR", "", ".")
".E.L.I.X.I.R."
iex> String.replace("ELIXIR", "", "")
"ELIXIR"