Sys.Text
Sys.Text collects helpers for working with text: changing case, encoding for URLs and HTML, converting between text encodings, formatting numbers, generating random strings and UUIDs, and validating IBANs. Server-side code also gets Handlebars templates, YAML conversion and fuzzy string matching.
Most functions are available in all code. The ones marked Server exist only in server-side code.
Availability: Everywhere
Functions
Section titled “Functions”capitalizeFirstLetter()
Section titled “capitalizeFirstLetter()”capitalizeFirstLetter(text: string): stringReturns the text with its first character in upper case. An empty or missing text is returned unchanged.
| Parameter | Type | Description |
|---|---|---|
text | string | Text to change. |
Returns: string · Availability: Everywhere
uncapitalizeFirstLetter()
Section titled “uncapitalizeFirstLetter()”uncapitalizeFirstLetter(text: string): stringReturns the text with its first character in lower case. An empty or missing text is returned unchanged.
| Parameter | Type | Description |
|---|---|---|
text | string | Text to change. |
Returns: string · Availability: Everywhere
sentenceCase()
Section titled “sentenceCase()”sentenceCase(text: string, capitalizeWords?: boolean, capitalizeFirstWord?: boolean): stringConverts every upper-case letter to lower case, removes leading spaces, and then upper-cases the first letter. It does not insert spaces between the words of a camel-case name: helloWorld becomes Helloworld.
| Parameter | Type | Description |
|---|---|---|
text | string | Text to change. |
capitalizeWords | boolean | If true, upper-case letters are kept instead of being lowered. Default: false. |
capitalizeFirstWord | boolean | If false, the first letter is not upper-cased. Default: true. |
Returns: string · Availability: Everywhere
Note
Runs of two or more spaces inside the text are removed completely, which joins the neighbouring words: hello world becomes Helloworld.
escapeQuotes()
Section titled “escapeQuotes()”escapeQuotes(expression: any): anyConverts the value to text and puts a backslash in front of every double quote. null and undefined return an empty string.
| Parameter | Type | Description |
|---|---|---|
expression | any | Value to escape. |
Returns: any (a string at runtime) · Availability: Everywhere
parseRegExp()
Section titled “parseRegExp()”parseRegExp(regexpAsString: string): RegExpTurns a regular expression written as text, such as /^[a-z]+$/i, into a RegExp object.
| Parameter | Type | Description |
|---|---|---|
regexpAsString | string | The expression in the form /pattern/flags. |
Returns: RegExp · Availability: Everywhere
Note
A string that is not enclosed in slashes does not cause an error: it produces an empty regular expression, which matches every string.
calculateNextFreeName()
Section titled “calculateNextFreeName()”calculateNextFreeName<T>(desiredName: string | ((suffix: string) => string), existingItems: T[], nameMapping: (item: T) => string, suffixWithAtLeastDigits?: number, needsToBeLargerThanAllExisting?: boolean): stringReturns a name that is not yet used by any of the existing items, by appending a counter to the desired name. Use it to propose names such as Copy, Copy1, Copy2.
| Parameter | Type | Description |
|---|---|---|
desiredName | string | ((suffix: string) => string) | The base name, or a function that builds the name from the counter suffix (for counters in the middle of the name). |
existingItems | T[] | Items whose names are already taken. |
nameMapping | (item: T) => string | Returns the name of an existing item. |
suffixWithAtLeastDigits | number | If greater than 0, a counter is always appended, padded with zeros to this many digits (for example Item01). If 0, the desired name is returned unchanged when it is free. Default: 0. |
needsToBeLargerThanAllExisting | boolean | If true, the counter starts after the number at the end of the alphabetically last existing name. Default: false. |
Returns: string · Availability: Everywhere
generateRandomString()
Section titled “generateRandomString()”generateRandomString(length: number, options?: RandomStringOptions): stringGenerates a random string, for example for initial passwords, test data or download tokens.
| Parameter | Type | Description |
|---|---|---|
length | number | Number of characters, not counting group separators. |
options | RandomStringOptions | Alphabet, excluded characters and grouping. If omitted, lower-case and upper-case letters, digits and special characters are used. |
RandomStringOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
alphabet | string | object | No | Either a string of all allowed characters, or an object choosing character classes: lowerCase, upperCase and digits (each boolean), and specialCharacters (true for -+"*%&/()=?@#$<>, or a string of your own special characters). |
removeAmbiguousCharacters | boolean | string | No | true removes iIlLoO01; a string removes exactly those characters. Default: true when alphabet is an object that includes lowerCase or upperCase, otherwise false. |
removeCharactersFromAlphabet | string | No | Further characters to remove from the alphabet. |
ensureAllAlphabetTypesAreUsed | boolean | No | If true, the result contains at least one character of every chosen class, which helps meet password rules. Default: true. |
group | object | No | Splits the result into groups: size is a group length (repeated) or an array of exact group lengths, and separator is the text inserted between groups. Separators do not count towards length. |
Returns: string · Availability: Everywhere
The function throws an error if length is smaller than the number of character classes that must appear, if a chosen class is empty after removing characters, or if fewer than two characters remain in the alphabet.
Note
The characters are picked with Math.random(), which is not a cryptographically secure random generator. Ambiguous characters are only removed by default when you pass an alphabet object; with no options at all they are included.
encodeUrl()
Section titled “encodeUrl()”encodeUrl: typeof encodeURIComponentEncodes text for use as one component of a URL, such as a query parameter value. It is the standard encodeURIComponent function.
| Parameter | Type | Description |
|---|---|---|
uriComponent | string | number | boolean | Value to encode. |
Returns: string · Availability: Everywhere
decodeUrl()
Section titled “decodeUrl()”decodeUrl: typeof decodeURIComponentDecodes a URL component encoded with encodeUrl(). It is the standard decodeURIComponent function.
| Parameter | Type | Description |
|---|---|---|
encodedURIComponent | string | Value to decode. |
Returns: string · Availability: Everywhere
convert()
Section titled “convert()”convert(input: string, from: TextConversionType, to: TextConversionType): stringconvert(input: ArrayBuffer, from: 'binary', to: TextConversionType): stringconvert(input: string, from: TextConversionType, to: 'binary'): ArrayBufferconvert(input: ArrayBuffer, from: 'binary', to: 'binary'): ArrayBufferConverts data between text encodings and binary data, for example from Base64 to hex, or from a string to bytes. binary stands for raw bytes; every other value names how the text is encoded.
In server-side code, binary data is a Node.js Buffer instead of an ArrayBuffer, and these overloads apply:
convert(input: string, from: TextConversionType, to: TextConversionType): stringconvert(input: Buffer, from: 'binary', to: TextConversionType): stringconvert(input: string | Buffer, from: ConversionType, to: TextConversionType): stringconvert(input: string, from: TextConversionType, to: 'binary'): Bufferconvert(input: Buffer, from: 'binary', to: 'binary'): Bufferconvert(input: string | Buffer, from: ConversionType, to: 'binary'): Bufferconvert(input: string | Buffer, from: ConversionType, to: ConversionType): string | Buffer| Parameter | Type | Description |
|---|---|---|
input | string | ArrayBuffer | Buffer | Data to convert: text, or bytes when from is binary. |
from | ConversionType | Encoding of the input. |
to | ConversionType | Encoding of the result. |
Returns: string, or binary data when to is binary · Availability: Everywhere
const base64 = Sys.Text.convert('Hello', 'utf-8', 'base64') // 'SGVsbG8='const hex = Sys.Text.convert(base64, 'base64', 'hex') // '48656c6c6f'Note
In client-side code, utf-8 text is treated as one byte per character, as ascii is. Characters up to U+00FF are converted as single bytes instead of UTF-8 sequences, so the result differs from the server-side result, and converting a character above U+00FF to base64 throws an error.
truncateWithEllipsis()
Section titled “truncateWithEllipsis()”truncateWithEllipsis(text: string, maxLength: number): stringShortens text that is longer than maxLength to maxLength characters, the last three of which are .... Shorter text is returned unchanged.
| Parameter | Type | Description |
|---|---|---|
text | string | Text to shorten. |
maxLength | number | Maximum length of the result, including the dots. |
Returns: string · Availability: Everywhere
isValidIban()
Section titled “isValidIban()”isValidIban(iban: string): booleanChecks whether a text is a valid IBAN. Spaces are ignored and letters may be in lower case. The check covers the length for the country code and the check digits.
| Parameter | Type | Description |
|---|---|---|
iban | string | The IBAN to check. |
Returns: boolean, false also for an empty value or an unknown country code · Availability: Everywhere
encodeHtml()
Section titled “encodeHtml()”encodeHtml(text: string): stringReplaces characters that have a meaning in HTML, such as <, >, & and quotes, with HTML entities, so that the text can be inserted into HTML safely. It uses the html-entities package.
In server-side code, the function is the package’s encode function itself and accepts options:
encodeHtml(text: string | undefined | null, { mode, numeric, level }?: EncodeOptions): string| Parameter | Type | Description |
|---|---|---|
text | string | Text to encode. On the server, also null or undefined, which give an empty string. |
options | EncodeOptions | Server only. Which characters to encode, and how. |
EncodeOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
mode | 'specialChars' | 'nonAscii' | 'nonAsciiPrintable' | 'nonAsciiPrintableOnly' | 'extensive' | No | Which characters are encoded. Default: specialChars, only the characters with a meaning in HTML. |
numeric | 'decimal' | 'hexadecimal' | No | Format of numeric entities. |
level | 'xml' | 'html4' | 'html5' | 'all' | No | Which set of named entities is used. |
Returns: string · Availability: Everywhere
decodeHtml()
Section titled “decodeHtml()”decodeHtml(text: string | undefined | null, { level, scope }?: DecodeOptions): stringReplaces HTML entities in the text with the characters they stand for. It is the decode function of the html-entities package.
| Parameter | Type | Description |
|---|---|---|
text | string | undefined | null | Text to decode. |
options | DecodeOptions | How entities are recognized. |
DecodeOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
level | 'xml' | 'html4' | 'html5' | 'all' | No | Which set of named entities is recognized. |
scope | 'strict' | 'body' | 'attribute' | No | How entities without a closing semicolon are treated, following the rules for HTML body text or attribute values. |
Returns: string · Availability: Server
prettyPrintJson()
Section titled “prettyPrintJson()”prettyPrintJson(value: any, options?: FormatOptions): stringFormats a value as indented JSON and returns it as HTML, with keys and values wrapped in elements that carry CSS classes for syntax colouring. It uses the pretty-print-json package.
| Parameter | Type | Description |
|---|---|---|
value | any | Value to format. |
options | FormatOptions | Formatting options. |
FormatOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
indent | number | No | Number of spaces per indentation level. |
lineNumbers | boolean | No | Wraps the output in an ordered list, giving each line a number. |
linkUrls | boolean | No | Turns URL strings into links. |
linksNewTab | boolean | No | Opens those links in a new browser tab. |
quoteKeys | boolean | No | Puts keys in double quotes. |
trailingCommas | boolean | No | Adds a comma after the last item of objects and arrays. |
Returns: string (HTML) · Availability: Everywhere
convertToSingular()
Section titled “convertToSingular()”convertToSingular(word: string): stringConverts a simple English plural into its singular: a final ies becomes y, and a final s is removed. Other words are returned unchanged.
| Parameter | Type | Description |
|---|---|---|
word | string | Word to convert. |
Returns: string · Availability: Everywhere
Note
Words ending in children are converted incorrectly: children becomes childd.
concatWithSpace()
Section titled “concatWithSpace()”concatWithSpace(...args: string[]): stringJoins the texts with a single space, leaving out empty strings, null and undefined. Use it to build names such as first name plus last name when either part may be missing.
| Parameter | Type | Description |
|---|---|---|
args | string[] | Texts to join. |
Returns: string · Availability: Everywhere
concatWithSeparator()
Section titled “concatWithSeparator()”concatWithSeparator(separator: string, ...args: string[]): stringJoins the texts with the given separator, leaving out empty strings, null and undefined.
| Parameter | Type | Description |
|---|---|---|
separator | string | Text placed between two values, for example ', '. |
args | string[] | Texts to join. |
Returns: string · Availability: Everywhere
createUuid()
Section titled “createUuid()”createUuid(): `${string}-${string}-${string}-${string}-${string}`Creates a random version 4 UUID, such as 3b241101-e2bb-4255-8caf-4136c566a962. In client-side code, browsers provide this only on pages served over HTTPS or from localhost.
Returns: string · Availability: Everywhere
formatAsCurrency()
Section titled “formatAsCurrency()”formatAsCurrency(value: number, locale?: string): stringFormats a number with exactly two decimal places and the thousands separator of the locale. No currency symbol is added.
| Parameter | Type | Description |
|---|---|---|
value | number | Amount to format. |
locale | string | BCP 47 locale such as en-US. Default: de-CH. |
Returns: string · Availability: Everywhere
formatAsDecimalNumber()
Section titled “formatAsDecimalNumber()”formatAsDecimalNumber(value: number, decimals: number, locale?: string): stringFormats a number with exactly the given number of decimal places and the separators of the locale.
| Parameter | Type | Description |
|---|---|---|
value | number | Number to format. |
decimals | number | Number of decimal places. |
locale | string | BCP 47 locale such as en-US. Default: de-CH. |
Returns: string · Availability: Everywhere
fillHandlebarsTemplate()
Section titled “fillHandlebarsTemplate()”fillHandlebarsTemplate<T extends string>(template: T, vars: InferInputFromHandlebarsTemplate<T>): stringFills a Handlebars template with values and returns the resulting text. When the template is a string literal, the type of vars is derived from the placeholders, so missing values show up as type errors. Getters and methods of class instances, such as Entity objects, can be used in the template.
| Parameter | Type | Description |
|---|---|---|
template | T | The template text, with placeholders such as {{name}}. |
vars | InferInputFromHandlebarsTemplate<T> | Values for the placeholders. |
Returns: string · Availability: Server
const text = Sys.Text.fillHandlebarsTemplate( 'Dear {{customer.name}}, your order {{orderNumber}} has shipped.', { customer: { name: 'Ann Smith' }, orderNumber: 'A-1042' },)Handlebars escapes HTML characters in {{value}}; use {{{value}}} to insert a value unescaped.
levenshteinDistance()
Section titled “levenshteinDistance()”levenshteinDistance(a: string, b: string): numberReturns the Levenshtein distance between two strings: the number of single-character insertions, deletions and substitutions needed to turn one into the other. It is the distance function of fastest-levenshtein.
| Parameter | Type | Description |
|---|---|---|
a | string | First string. |
b | string | Second string. |
Returns: number · Availability: Server
levenshteinClosest()
Section titled “levenshteinClosest()”levenshteinClosest(str: string, arr: readonly string[]): stringReturns the string from the list that has the smallest Levenshtein distance to str. It is the closest function of fastest-levenshtein.
| Parameter | Type | Description |
|---|---|---|
str | string | String to match. |
arr | readonly string[] | Candidates. |
Returns: string · Availability: Server
toYaml()
Section titled “toYaml()”toYaml(data: any): stringConverts a value to YAML text, using the yaml package.
| Parameter | Type | Description |
|---|---|---|
data | any | Value to convert. |
Returns: string · Availability: Server
fromYaml()
Section titled “fromYaml()”fromYaml(yaml: string): anyParses YAML text into a value, using the yaml package.
| Parameter | Type | Description |
|---|---|---|
yaml | string | YAML text to parse. |
Returns: any · Availability: Server
Properties
Section titled “Properties”Handlebars
Section titled “Handlebars”The Handlebars template engine (npm package handlebars, version ^4.7.7), re-exported as is. Use it when you need more than fillHandlebarsTemplate(), for example helpers or partials.
const template = Sys.Text.Handlebars.compile('Hello {{name}}')const text = template({ name: 'Ann' })Type: typeof Handlebars · Availability: Server
The fuzzball fuzzy string matching library (npm package fuzzball, version ^2.2.6), re-exported as is. It scores how similar two strings are, from 0 to 100.
const score = Sys.Text.Fuzz.ratio('Lowgile AG', 'Lowgile Ltd')Type: typeof import('fuzzball') · Availability: Server
TextConversionType
Section titled “TextConversionType”type TextConversionType = 'ascii' | 'utf-8' | 'base64' | 'hex'Text encodings accepted by convert().
Availability: Everywhere
ConversionType
Section titled “ConversionType”type ConversionType = TextConversionType | 'binary'All values accepted by convert(): the text encodings plus binary for raw bytes.
Availability: Everywhere
InferInputFromHandlebarsTemplate
Section titled “InferInputFromHandlebarsTemplate”type InferInputFromHandlebarsTemplate<T extends string> = FlattenVars<ExtractVarsFromTemplateInternal<T>> & Record<string, any>The type of the values object for a template literal: one property per {{placeholder}}, nested objects for {{object.property}}, and an array for each {{#each list}} block. Any further properties are allowed.
Availability: Server
ParseHtmlOptions
Section titled “ParseHtmlOptions”The Options type of the node-html-parser package. Sys.Text exports the type but no function that parses HTML.
Availability: Server
HTMLElement
Section titled “HTMLElement”The HTMLElement class type of the node-html-parser package, exported as a type only.
Availability: Server