Skip to content

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

capitalizeFirstLetter(text: string): string

Returns the text with its first character in upper case. An empty or missing text is returned unchanged.

ParameterTypeDescription
textstringText to change.

Returns: string · Availability: Everywhere

uncapitalizeFirstLetter(text: string): string

Returns the text with its first character in lower case. An empty or missing text is returned unchanged.

ParameterTypeDescription
textstringText to change.

Returns: string · Availability: Everywhere

sentenceCase(text: string, capitalizeWords?: boolean, capitalizeFirstWord?: boolean): string

Converts 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.

ParameterTypeDescription
textstringText to change.
capitalizeWordsbooleanIf true, upper-case letters are kept instead of being lowered. Default: false.
capitalizeFirstWordbooleanIf 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(expression: any): any

Converts the value to text and puts a backslash in front of every double quote. null and undefined return an empty string.

ParameterTypeDescription
expressionanyValue to escape.

Returns: any (a string at runtime) · Availability: Everywhere

parseRegExp(regexpAsString: string): RegExp

Turns a regular expression written as text, such as /^[a-z]+$/i, into a RegExp object.

ParameterTypeDescription
regexpAsStringstringThe 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<T>(desiredName: string | ((suffix: string) => string), existingItems: T[], nameMapping: (item: T) => string, suffixWithAtLeastDigits?: number, needsToBeLargerThanAllExisting?: boolean): string

Returns 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.

ParameterTypeDescription
desiredNamestring | ((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).
existingItemsT[]Items whose names are already taken.
nameMapping(item: T) => stringReturns the name of an existing item.
suffixWithAtLeastDigitsnumberIf 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.
needsToBeLargerThanAllExistingbooleanIf true, the counter starts after the number at the end of the alphabetically last existing name. Default: false.

Returns: string · Availability: Everywhere

generateRandomString(length: number, options?: RandomStringOptions): string

Generates a random string, for example for initial passwords, test data or download tokens.

ParameterTypeDescription
lengthnumberNumber of characters, not counting group separators.
optionsRandomStringOptionsAlphabet, excluded characters and grouping. If omitted, lower-case and upper-case letters, digits and special characters are used.

RandomStringOptions fields

FieldTypeRequiredDescription
alphabetstring | objectNoEither 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).
removeAmbiguousCharactersboolean | stringNotrue removes iIlLoO01; a string removes exactly those characters. Default: true when alphabet is an object that includes lowerCase or upperCase, otherwise false.
removeCharactersFromAlphabetstringNoFurther characters to remove from the alphabet.
ensureAllAlphabetTypesAreUsedbooleanNoIf true, the result contains at least one character of every chosen class, which helps meet password rules. Default: true.
groupobjectNoSplits 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: typeof encodeURIComponent

Encodes text for use as one component of a URL, such as a query parameter value. It is the standard encodeURIComponent function.

ParameterTypeDescription
uriComponentstring | number | booleanValue to encode.

Returns: string · Availability: Everywhere

decodeUrl: typeof decodeURIComponent

Decodes a URL component encoded with encodeUrl(). It is the standard decodeURIComponent function.

ParameterTypeDescription
encodedURIComponentstringValue to decode.

Returns: string · Availability: Everywhere

convert(input: string, from: TextConversionType, to: TextConversionType): string
convert(input: ArrayBuffer, from: 'binary', to: TextConversionType): string
convert(input: string, from: TextConversionType, to: 'binary'): ArrayBuffer
convert(input: ArrayBuffer, from: 'binary', to: 'binary'): ArrayBuffer

Converts 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): string
convert(input: Buffer, from: 'binary', to: TextConversionType): string
convert(input: string | Buffer, from: ConversionType, to: TextConversionType): string
convert(input: string, from: TextConversionType, to: 'binary'): Buffer
convert(input: Buffer, from: 'binary', to: 'binary'): Buffer
convert(input: string | Buffer, from: ConversionType, to: 'binary'): Buffer
convert(input: string | Buffer, from: ConversionType, to: ConversionType): string | Buffer
ParameterTypeDescription
inputstring | ArrayBuffer | BufferData to convert: text, or bytes when from is binary.
fromConversionTypeEncoding of the input.
toConversionTypeEncoding 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(text: string, maxLength: number): string

Shortens text that is longer than maxLength to maxLength characters, the last three of which are .... Shorter text is returned unchanged.

ParameterTypeDescription
textstringText to shorten.
maxLengthnumberMaximum length of the result, including the dots.

Returns: string · Availability: Everywhere

isValidIban(iban: string): boolean

Checks 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.

ParameterTypeDescription
ibanstringThe IBAN to check.

Returns: boolean, false also for an empty value or an unknown country code · Availability: Everywhere

encodeHtml(text: string): string

Replaces 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
ParameterTypeDescription
textstringText to encode. On the server, also null or undefined, which give an empty string.
optionsEncodeOptionsServer only. Which characters to encode, and how.

EncodeOptions fields

FieldTypeRequiredDescription
mode'specialChars' | 'nonAscii' | 'nonAsciiPrintable' | 'nonAsciiPrintableOnly' | 'extensive'NoWhich characters are encoded. Default: specialChars, only the characters with a meaning in HTML.
numeric'decimal' | 'hexadecimal'NoFormat of numeric entities.
level'xml' | 'html4' | 'html5' | 'all'NoWhich set of named entities is used.

Returns: string · Availability: Everywhere

decodeHtml(text: string | undefined | null, { level, scope }?: DecodeOptions): string

Replaces HTML entities in the text with the characters they stand for. It is the decode function of the html-entities package.

ParameterTypeDescription
textstring | undefined | nullText to decode.
optionsDecodeOptionsHow entities are recognized.

DecodeOptions fields

FieldTypeRequiredDescription
level'xml' | 'html4' | 'html5' | 'all'NoWhich set of named entities is recognized.
scope'strict' | 'body' | 'attribute'NoHow entities without a closing semicolon are treated, following the rules for HTML body text or attribute values.

Returns: string · Availability: Server

prettyPrintJson(value: any, options?: FormatOptions): string

Formats 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.

ParameterTypeDescription
valueanyValue to format.
optionsFormatOptionsFormatting options.

FormatOptions fields

FieldTypeRequiredDescription
indentnumberNoNumber of spaces per indentation level.
lineNumbersbooleanNoWraps the output in an ordered list, giving each line a number.
linkUrlsbooleanNoTurns URL strings into links.
linksNewTabbooleanNoOpens those links in a new browser tab.
quoteKeysbooleanNoPuts keys in double quotes.
trailingCommasbooleanNoAdds a comma after the last item of objects and arrays.

Returns: string (HTML) · Availability: Everywhere

convertToSingular(word: string): string

Converts a simple English plural into its singular: a final ies becomes y, and a final s is removed. Other words are returned unchanged.

ParameterTypeDescription
wordstringWord to convert.

Returns: string · Availability: Everywhere

Note

Words ending in children are converted incorrectly: children becomes childd.

concatWithSpace(...args: string[]): string

Joins 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.

ParameterTypeDescription
argsstring[]Texts to join.

Returns: string · Availability: Everywhere

concatWithSeparator(separator: string, ...args: string[]): string

Joins the texts with the given separator, leaving out empty strings, null and undefined.

ParameterTypeDescription
separatorstringText placed between two values, for example ', '.
argsstring[]Texts to join.

Returns: string · Availability: Everywhere

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(value: number, locale?: string): string

Formats a number with exactly two decimal places and the thousands separator of the locale. No currency symbol is added.

ParameterTypeDescription
valuenumberAmount to format.
localestringBCP 47 locale such as en-US. Default: de-CH.

Returns: string · Availability: Everywhere

formatAsDecimalNumber(value: number, decimals: number, locale?: string): string

Formats a number with exactly the given number of decimal places and the separators of the locale.

ParameterTypeDescription
valuenumberNumber to format.
decimalsnumberNumber of decimal places.
localestringBCP 47 locale such as en-US. Default: de-CH.

Returns: string · Availability: Everywhere

fillHandlebarsTemplate<T extends string>(template: T, vars: InferInputFromHandlebarsTemplate<T>): string

Fills 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.

ParameterTypeDescription
templateTThe template text, with placeholders such as {{name}}.
varsInferInputFromHandlebarsTemplate<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(a: string, b: string): number

Returns 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.

ParameterTypeDescription
astringFirst string.
bstringSecond string.

Returns: number · Availability: Server

levenshteinClosest(str: string, arr: readonly string[]): string

Returns the string from the list that has the smallest Levenshtein distance to str. It is the closest function of fastest-levenshtein.

ParameterTypeDescription
strstringString to match.
arrreadonly string[]Candidates.

Returns: string · Availability: Server

toYaml(data: any): string

Converts a value to YAML text, using the yaml package.

ParameterTypeDescription
dataanyValue to convert.

Returns: string · Availability: Server

fromYaml(yaml: string): any

Parses YAML text into a value, using the yaml package.

ParameterTypeDescription
yamlstringYAML text to parse.

Returns: any · Availability: Server

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

type TextConversionType = 'ascii' | 'utf-8' | 'base64' | 'hex'

Text encodings accepted by convert().

Availability: Everywhere

type ConversionType = TextConversionType | 'binary'

All values accepted by convert(): the text encodings plus binary for raw bytes.

Availability: Everywhere

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

The Options type of the node-html-parser package. Sys.Text exports the type but no function that parses HTML.

Availability: Server

The HTMLElement class type of the node-html-parser package, exported as a type only.

Availability: Server