strings

Text utilities for slicing, splitting, joining, case conversion, and searching.

import strings

Remember that in Bern a string is a list of characters, so list operators apply to strings too - "ab" <> "cd" is "abcd", and "hello"[0] is 'h'. The strings library adds the higher-level text operations on top.

Extraction

substring(string, start, end) → string

The slice from index start up to (but not including) end.

substring("Hello", 1, 4)
-- Output: "ell"
char_at(string, index) → char

The character at index (the same as indexing with []).

char_at("Bern", 0)
-- Output: 'B'

Split & join

split(string, delimiter) → list

Break a string into a list of pieces on each occurrence of delimiter.

split("a,b,c", ",")
-- Output: ["a", "b", "c"]
join(list, delimiter) → string

The inverse of split: glue a list of strings together with a separator.

join(["a", "b", "c"], "-")
-- Output: "a-b-c"

Case conversion

to_upper(string) → string

Uppercase every letter.

to_upper("bern")
-- Output: "BERN"
to_lower(string) → string

Lowercase every letter.

to_lower("BERN")
-- Output: "bern"
char_to_upper(char) → char

Uppercase a single character (non-letters pass through unchanged).

char_to_upper('a')
-- Output: 'A'
char_to_lower(char) → char

Lowercase a single character.

char_to_lower('Z')
-- Output: 'z'

Modification

trim(string) → string

Remove leading and trailing spaces, newlines, and tabs.

trim("  hello  ")
-- Output: "hello"
replace(string, old, new) → string

Replace every occurrence of old with new.

replace("hello world", "world", "Bern")
-- Output: "hello Bern"

Numbers

from_int(int) → string

Render an integer as a string (handles negatives). The counterpart of core's to_int.

from_int(-42)
-- Output: "-42"
"v" + from_int(2)
-- Output: "v2"

Putting it together

The functions chain well for cleaning and reshaping text. Here a messy CSV-ish line is split, trimmed, normalized, and rejoined:

Normalizing a line of tags

import core
import strings

line = "  Bern , Lang ,DOCS  "

tags = split(line, ",")
    )| map(\t -> to_lower(trim(t)))

clean = join(tags, ", ")
-- Output: "bern, lang, docs"

And a tiny "slugify" that combines to_lower, replace, and trim:

Building a URL slug

import strings

def slugify(title) do
    lower = to_lower(trim(title))
    return replace(lower, " ", "-")
end

slugify("  Getting Started With Bern ")
-- Output: "getting-started-with-bern"