ExUtils.Strings (ExUtils v3.0.0)

Copy Markdown View Source

Helpers for working with strings.

Summary

Functions

Returns true for nil, empty strings, and whitespace-only strings.

Returns true for strings that contain non-whitespace characters.

Trims leading and trailing whitespace.

Truncates a string to the given length.

Functions

blank?(str)

(since 3.0.0)
@spec blank?(String.t() | nil) :: boolean()

Returns true for nil, empty strings, and whitespace-only strings.

Unlike other blank-based functions, this is not configurable and only accepts string or nil inputs. If you're looking for a generic, configurable version, see ExUtils.Terms.blank?/2.

Examples

iex> blank?("hello world")
false
iex> blank?("      ")
true
iex> blank?(nil)
true

present?(string)

(since 3.0.0)
@spec present?(String.t() | nil) :: boolean()

Returns true for strings that contain non-whitespace characters.

This is the opposite of blank?/1, and just like it, this is also not configurable. If you're looking for a generic version, see ExUtils.Terms.present?/2.

Examples

iex> present?("hello world")
true
iex> present?("      ")
false
iex> present?(nil)
false

trim(string)

(since 3.0.0)
@spec trim(String.t() | nil) :: String.t() | nil

Trims leading and trailing whitespace.

This is the same as String.trim/1 but also handles nil inputs, returning them as-is.

Examples

iex> trim("  hello  ")
"hello"
iex> trim(nil)
nil

truncate(string, length, opts \\ [])

(since 3.0.0)
@spec truncate(String.t(), non_neg_integer(), Keyword.t()) :: String.t()

Truncates a string to the given length.

This counts the given string's graphemes and truncates at most length, including the suffix. Before appending the suffix, this also trims trailing whitespace by default.

Strings already within the limit are returned as given.

Options

  • :suffix - Text appended on truncation. Defaults to "…". A suffix longer than the limit is itself truncated.
  • :trim - Trim trailing whitespace before appending suffix. Defaults to true.

Examples

iex> truncate("Hello world", 7)
"Hello…"
iex> truncate("Hello", 4, suffix: "..")
"He.."
iex> truncate("Hello", 4, suffix: nil)
"Hell"