String.slice

You're seeing just the function slice, go back to String module for more information.

Specs

slice(t(), Range.t()) :: t()

Returns a substring from the offset given by the start of the range to the offset given by the end of the range.

If the start of the range is not a valid offset for the given string or if the range is in reverse order, returns "".

If the start or end of the range is negative, the whole string is traversed first in order to convert the negative indices into positive ones.

Remember this function works with Unicode graphemes and considers the slices to represent grapheme offsets. If you want to split on raw bytes, check Kernel.binary_part/3 instead.

Examples

iex> String.slice("elixir", 1..3)
"lix"

iex> String.slice("elixir", 1..10)
"lixir"

iex> String.slice("elixir", -4..-1)
"ixir"

iex> String.slice("elixir", -4..6)
"ixir"

For ranges where start > stop, you need to explicit mark them as increasing:

iex> String.slice("elixir", 2..-1//1)
"ixir"

iex> String.slice("elixir", 1..-2//1)
"lixi"

If values are out of bounds, it returns an empty string:

iex> String.slice("elixir", 10..3)
""

iex> String.slice("elixir", -10..-7)
""

iex> String.slice("a", 0..1500)
"a"

iex> String.slice("a", 1..1500)
""
Link to this function

slice(string, start, length)

View Source

Specs

slice(t(), integer(), non_neg_integer()) :: grapheme()

Returns a substring starting at the offset start, and of the given length.

If the offset is greater than string length, then it returns "".

Remember this function works with Unicode graphemes and considers the slices to represent grapheme offsets. If you want to split on raw bytes, check Kernel.binary_part/3 instead.

Examples

iex> String.slice("elixir", 1, 3)
"lix"

iex> String.slice("elixir", 1, 10)
"lixir"

iex> String.slice("elixir", 10, 3)
""

iex> String.slice("elixir", -4, 4)
"ixir"

iex> String.slice("elixir", -10, 3)
""

iex> String.slice("a", 0, 1500)
"a"

iex> String.slice("a", 1, 1500)
""

iex> String.slice("a", 2, 1500)
""