query
On this page

trimWith

lib.trimWith

Docs pulled from | This Revision | about 1 hour ago


Remove leading and/or trailing whitespace from a string s.

To remove both leading and trailing whitespace, you can also use trim

Whitespace is defined as any of the following characters: " ", "\t" "\r" "\n"

Inputs

config (Attribute set)
start
Whether to trim leading whitespace (false by default)
end
Whether to trim trailing whitespace (false by default)
s
The string to trim

Type

trimWith :: { start :: Bool; end :: Bool } -> String -> String

Examples

lib.strings.trimWith usage example

trimWith { start = true; } "   hello, world!   "}
=> "hello, world!   "

trimWith { end = true; } "   hello, world!   "}
=> "   hello, world!"
(lib.strings.trimWith)

Noogle detected

Aliases

Implementation

The following is the current implementation of this function.

trimWith =
    {
      start ? false,
      end ? false,
    }:
    let
      # Define our own whitespace character class instead of using
      # `[:space:]`, which is not well-defined.
      chars = " \t\r\n";

      # To match up until trailing whitespace, we need to capture a
      # group that ends with a non-whitespace character.
      regex =
        if start && end then
          "[${chars}]*(.*[^${chars}])[${chars}]*"
        else if start then
          "[${chars}]*(.*)"
        else if end then
          "(.*[^${chars}])[${chars}]*"
        else
          "(.*)";
    in
    s:
    let
      # If the string was empty or entirely whitespace,
      # then the regex may not match and `res` will be `null`.
      res = match regex s;
    in
    optionalString (res != null) (head res);