Cuerdas String Manipulation Library

repository·master·Indexed 43 days ago

https://github.com/funcool/cuerdas

A null-safe string manipulation library for Clojure and ClojureScript designed to fill gaps in the standard library. It provides high-performance concatenation via the `concat` macro, string interpolation with `istr` and `ffmt`, casing conversions (camel, kebab, snake, pascal, human, title), and utilities for HTML tag stripping, whitespace management, and string validation.

Tokens
3K
Snippets
19
Records
19
Agent score
6%

What's inside Cuerdas

  1. Quick start with Cuerdas

    master

    To begin using the library, require cuerdas.core in your namespace. Most users alias it as str to avoid conflicts with the standard clojure.string library.

    Important Design Note: Cuerdas is designed to be null-safe. Any function expecting a string that receives nil will return nil instead of throwing an error.

    (ns my.namespace
      (:require [cuerdas.core :as str]))
  2. Run tests in Clojure or ClojureScript

    master

    Cuerdas uses Reader Conditionals to target specific implementations for Clojure and ClojureScript. You can run the test suites for each environment using the following commands:

    For Clojure: Use the clojure CLI with the :dev:test alias.

    For ClojureScript: Install dependencies via yarn and then run the test script.

    # Run tests in Clojure
    clojure -X:dev:test
    
    # Run tests in ClojureScript
    yarn install
    yarn test
  3. Self-host ClojureScript with Cuerdas

    master

    You can self-host ClojureScript using lumo by passing the dependency via -Sdeps. Replace X.Y.Z with the desired version.

    lumo -c $(clojure -Srepro -Sdeps '{:deps {funcool/cuerdas {:mvn/version "X.Y.Z"}}}' -Spath)
  4. Manipulate string whitespace and trimming

    master

    Functions for cleaning up whitespace:

    • clean: Trims and replaces multiple spaces with a single space.
    • collapse-whitespace: Converts any adjacent whitespace characters to a single space.
    • ltrim: Removes whitespace (or specific characters) from the left.
    • rtrim: Removes whitespace (or specific characters) from the right.
    • trim: Removes whitespace (or specific characters) from both ends.
    • strip-newlines: Replaces newlines with a single space.
    (str/clean "  a   b   ")           ; => "a b"
    (str/collapse-whitespace "a\n\nb") ; => "a b"
    (str/ltrim "-foo-" "-")           ; => "foo-"
    (str/trim " foo ")                 ; => "foo"
  5. Validate alphanumeric and alpha characters

    master

    Use these functions to check the content of a string:

    • alnum?: Returns true if the string contains only alphanumeric characters.
    • alpha?: Returns true if the string contains only alpha characters.
    (str/alnum? "Test123") ; => true
    (str/alpha? "Test")     ; => true
  6. Search and replace in strings

    master

    Functions for finding and modifying content:

    • index-of: Returns the index of a value (string or char).
    • last-index-of: Returns the last index of a value.
    • includes?: Checks if a string includes a substring.
    • replace: Replaces all instances of a match.
    • replace-first: Replaces only the first instance of a match.
    (str/index-of "foobar" "foo")      ; => 0
    (str/includes? "foobar" "bar")     ; => true
    (str/replace "aa bb aa" "aa" "kk") ; => "kk bb kk"
  7. Extract, slice, and split strings

    master

    Functions for breaking down strings:

    • chars: Returns a sequence of character strings.
    • lines: Returns a list of lines in the string.
    • slice: Extracts a section of a string by index.
    • split: Splits a string on a separator (string or regex) a limited number of times.
    • words: Returns a vector of words (defaults to [a-zA-Z0-9_-]+).
    (str/chars "bar")             ; => ["b" "a" "r"]
    (str/lines "foo\nbar")        ; => ["foo" "bar"]
    (str/slice "1234" 1 3)         ; => "23"
    (str/split "1 2 3" "" 2)     ; => ["1" "2 3"]
    (str/words "foo, bar")        ; => ["foo" "bar"]
  8. Pad and surround strings

    master

    Utilities for adding characters around a string:

    • pad: Pads a string to a specific length. Supports :left, :right, and :both types.
    • surround: Wraps a string with a specified delimiter.
    • quote: Wraps a string in quotes.
    • unquote: Removes quotes from a string.
    (str/pad "1" {:length 8 :padding "0" :type :right}) ; => "10000000"
    (str/surround "a" "-")                             ; => "-a-"
    (str/quote "a")                                      ; => "\"a\""
  9. Interpolate strings with istr

    master

    The istr macro provides string interpolation similar to ES6 template strings. It allows for symbol substitution and simple expression evaluation within a string. It is variadic and uses the fast concat macro internally.

    Note: Currently not compatible with self-hosted ClojureScript.

    (def value 30)
    (str/istr "value = ~{value}")
    ;; => "value = 30"
    
    (str/istr "value = ~(inc value)")
    ;; => "value = 31"
    
    ;; Variadic usage:
    (str/istr "the value " "is ~{value}")
    ;; => "the value is 30"
  10. Unindent lines in a string

    master

    The unindent function removes preceding whitespace from lines in a string. It can either strip whitespace automatically or use a user-supplied regex to determine what to remove.

    (str/unindent "first line\n            second line (indented)\n          another line")
    ;; yields:
    "first line\n  second line (indented)\nanother line"
  11. Strip HTML tags with strip-tags

    master

    The strip-tags function removes HTML tags from a string. You can optionally provide a list of tags to preserve.

    • (str/strip-tags input): Removes all tags.
    • (str/strip-tags input ["tag1" "tag2"]): Removes all tags except those specified in the collection.
    (str/strip-tags "<p>just <b>some</b> text</p>")
    ;; => "just some text"
    
    (str/strip-tags "<p>just <b>some</b> text</p>" ["p"])
    ;; => "just <b>some</b> text"