Qx.String (qx v0.2.0)

View Source

String helpers for the checks and transformations that come up in almost every project: presence testing, URL-safe slugs and display truncation.

Summary

Functions

Returns true when the value is nil, an empty string, or a string made up only of whitespace.

The inverse of blank?/1.

Converts a string into a lowercase, URL-safe slug.

Truncates a string to at most max graphemes, appending an ellipsis when the string was actually shortened.

Functions

blank?(string)

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

Returns true when the value is nil, an empty string, or a string made up only of whitespace.

Examples

iex> Qx.String.blank?(nil)
true

iex> Qx.String.blank?("   \n ")
true

iex> Qx.String.blank?(" hi ")
false

present?(string)

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

The inverse of blank?/1.

Examples

iex> Qx.String.present?("hi")
true

iex> Qx.String.present?("")
false

slugify(string, opts \\ [])

@spec slugify(
  String.t(),
  keyword()
) :: String.t()

Converts a string into a lowercase, URL-safe slug.

Accented characters are reduced to their base letter, runs of non-alphanumeric characters collapse into a single separator, and leading/trailing separators are trimmed.

Options

  • :separator - the string placed between words. Defaults to "-".

Examples

iex> Qx.String.slugify("Hello, World!")
"hello-world"

iex> Qx.String.slugify("  Creme Brulee  ")
"creme-brulee"

iex> Qx.String.slugify("Elixir Rocks", separator: "_")
"elixir_rocks"

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

@spec truncate(String.t(), pos_integer(), keyword()) :: String.t()

Truncates a string to at most max graphemes, appending an ellipsis when the string was actually shortened.

The omission counts towards max, so the result is never longer than max.

Options

  • :omission - the string appended when truncating. Defaults to "...".

Examples

iex> Qx.String.truncate("Hello, World!", 8)
"Hello..."

iex> Qx.String.truncate("Hello", 8)
"Hello"

iex> Qx.String.truncate("Hello, World!", 8, omission: "~")
"Hello, ~"