Skip to content

Commit 2eeef90

Browse files
committed
explain String.replace/4 :insert_replaced option
...and some other minor wording tweaks
1 parent 1ff6193 commit 2eeef90

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

lib/elixir/lib/string.ex

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -686,10 +686,10 @@ defmodule String do
686686
Returns a new binary created by replacing occurences of `pattern` in
687687
`subject` with `replacement`.
688688
689-
By default, it replaces all occurences, except if the `global` option is
689+
By default, it replaces all occurences, unless the `global` option is
690690
set to `false`.
691691
692-
A `pattern` may be a string or a regular expression.
692+
The `pattern` may be a string or a regular expression.
693693
694694
## Examples
695695
@@ -699,18 +699,20 @@ defmodule String do
699699
iex> String.replace("a,b,c", ",", "-", global: false)
700700
"a-b,c"
701701
702-
The pattern can also be a regular expression. In those cases, one can give `\N` or
702+
When the pattern is a regular expression, one can give `\N` or
703703
`\g{N}` in the `replacement` string to access a specific capture in the
704-
regex:
704+
regular expression:
705705
706706
iex> String.replace("a,b,c", ~r/,(.)/, ",\\1\\g{1}")
707707
"a,bb,cc"
708708
709709
Notice we had to escape the escape character `\`. By giving `\0`,
710710
one can inject the whole matched pattern in the replacement string.
711711
712-
When strings are used as a pattern, a developer can also use the
713-
replaced part inside the `replacement` via the `:insert_replaced` option:
712+
When the pattern is a string, a developer can use the replaced part inside
713+
the `replacement` by using the `:insert_replace` option and specifying the
714+
position(s) inside the `replacement` where the string pattern will be
715+
inserted:
714716
715717
iex> String.replace("a,b,c", "b", "[]", insert_replaced: 1)
716718
"a,[b],c"
@@ -721,6 +723,8 @@ defmodule String do
721723
iex> String.replace("a,b,c", ",", "[]", insert_replaced: [1, 1])
722724
"a[,,]b[,,]c"
723725
726+
If any position given in the `:insert_replace` option is larger than the
727+
replacement string, or is negative, an `ArgumentError` is raised.
724728
"""
725729
@spec replace(t, pattern | Regex.t, t, Keyword.t) :: t
726730
def replace(subject, pattern, replacement, options \\ []) when is_binary(replacement) do

0 commit comments

Comments
 (0)