Options
All
  • Public
  • Public/Protected
  • All
Menu

@thi.ng/strings

Index

Type aliases

FnS

FnS: FnU<string>

Stringer

Stringer<T>: (x: T, ...xs: any[]) => string

Type parameters

  • T

Type declaration

    • (x: T, ...xs: any[]): string
    • Parameters

      • x: T
      • Rest ...xs: any[]

      Returns string

Variables

Const ALPHA

ALPHA: Readonly<{}> = ...

Combination of UPPER and LOWER.

Const ALPHA_NUM

ALPHA_NUM: IObjectOf<boolean> = ...

Combination of ALPHA and DIGITS and '_'.

Const BOM

BOM: "" = "\ufeff"

UTF-8 Byte Order Mark character https://en.wikipedia.org/wiki/Byte_order_mark

Const DIGITS

DIGITS: Readonly<IObjectOf<boolean>> = ...

Object with 0-9 characters as keys and their values set to true. All others undefined.

Const ESCAPES

ESCAPES: Record<string, string> = ...

Const ESCAPES_REV

ESCAPES_REV: Record<number, string> = ...

Const HEX

HEX: Readonly<IObjectOf<boolean>> = ...

Object with hex digit characters (upper & lower case versions) as keys and their values set to true. All others undefined.

Const LOWER

LOWER: Readonly<IObjectOf<boolean>> = ...

Object with ASCII lowercase characters as keys and their values set to true. All others undefined.

Const PUNCTUATION

PUNCTUATION: Readonly<IObjectOf<boolean>> = ...

Object with ASCII punctuation characters as keys and their values set to true. All others undefined.

Const SPLIT_ANSI

SPLIT_ANSI: IWordSplit = ...

Wordwrap word splitting strategy for text containing ANSI control sequences.

Const SPLIT_PLAIN

SPLIT_PLAIN: IWordSplit = ...

(Default) wordwrap word splitting strategy for plain text.

Const UPPER

UPPER: Readonly<IObjectOf<boolean>> = ...

Object with ASCII uppercase characters as keys and their values set to true. All others undefined.

Const WS

WS: IObjectOf<boolean> = ...

Object with whitespace characters as keys and their values set to true. All others undefined.

Functions

Const B16

  • B16(x: number, ...xs: any[]): string
  • 16bit binary conversion preset.

    Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const B32

  • B32(x: number, ...xs: any[]): string
  • 32bit binary conversion preset.

    Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const B8

  • B8(x: number, ...xs: any[]): string
  • 8bit binary conversion preset.

    Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const U16

  • U16(x: number): string
  • 16bit hex conversion preset. Assumes unsigned inputs.

    Parameters

    • x: number

    Returns string

Const U24

  • U24(x: number): string
  • 24bit hex conversion preset. Assumes unsigned inputs.

    Parameters

    • x: number

    Returns string

Const U32

  • U32(x: number): string
  • 32bit hex conversion preset. Assumes unsigned inputs.

    Parameters

    • x: number

    Returns string

Const U64

  • U64(hi: number, lo: number): string
  • 64bit hex conversion preset (2x 32bit ints) Assumes unsigned inputs.

    Parameters

    • hi: number
    • lo: number

    Returns string

Const U8

  • U8(x: number): string
  • 8bit hex conversion preset. Assumes unsigned inputs.

    Parameters

    • x: number

    Returns string

Const Z2

  • Z2(x: any, length?: number): string
  • Zero-padded 2 digit formatter.

    Parameters

    • x: any
    • Optional length: number

    Returns string

Const Z3

  • Z3(x: any, length?: number): string
  • Zero-padded 3 digit formatter.

    Parameters

    • x: any
    • Optional length: number

    Returns string

Const Z4

  • Z4(x: any, length?: number): string
  • Zero-padded 4 digit formatter.

    Parameters

    • x: any
    • Optional length: number

    Returns string

Const bits

  • bits(x: number, ...xs: any[]): string
  • Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const bytes

  • bytes(x: number, ...xs: any[]): string
  • Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const camel

  • camel(x: string, ...xs: any[]): string
  • Converts a kebab-case or snake_case string into CamelCase. Uses - as default delimiter.

    Parameters

    • x: string

      -

    • Rest ...xs: any[]

    Returns string

Const capitalize

  • capitalize(a: string): string
  • String formatter which capitalizes first character.

    Parameters

    • a: string

    Returns string

Const center

  • center(lineWidth: number, pad?: string | number): Stringer<any>
  • Returns stringer which pads given input with ch (default: space) on both sides and returns fixed width string of given lineWidth. Returns string of only pad characters for any null or undefined values. If the string version of an input is > lineWidth, no centering is performed, but the string will be truncated to lineWidth.

    Note: The padding string can contain multiple characters.

    example
    center(20, "<>")(wrap(" ")("thi.ng"))
    // "<><><> thi.ng <><><>"
    

    Parameters

    • lineWidth: number

      target length

    • Optional pad: string | number

      pad character(s)

    Returns Stringer<any>

charRange

  • charRange(from: string | number, to: string | number): Generator<string, void, unknown>
  • Yields iterator of characters [from..to] (inclusive). Uses reverse ordering if to < from.

    Parameters

    • from: string | number

      -

    • to: string | number

      -

    Returns Generator<string, void, unknown>

Const computeCursorPos

  • computeCursorPos(str: string, pos: number, delim?: string | RegExp, offset?: number[]): number[]
  • Takes a string, linear index position and optional line split delimiter (or regexp, default: "\n"). Computes and returns position of index as cursor coords tuple: [line, column]

    remarks

    By default the returned coords are 1-based, but can be configured via optional offset arg (also in [line,column] order).

    example
    computeCursorPos("thi.ng\numbrella", 10);
    // [ 2, 4 ]
    
    // w/ custom offset
    computeCursorPos("thi.ng\numbrella", 10, "\n", [11, 1]);
    // [ 12, 4 ]
    

    Parameters

    • str: string

      -

    • pos: number

      -

    • delim: string | RegExp = "\n"

      -

    • offset: number[] = ...

      -

    Returns number[]

Const defFormat

  • defFormat(fmt: any[]): (...args: any[]) => string
  • HOF version of format.

    Parameters

    • fmt: any[]

    Returns (...args: any[]) => string

      • (...args: any[]): string
      • Parameters

        • Rest ...args: any[]

        Returns string

Const escape

  • escape(src: string): string
  • Escapes all non-ASCII characters (and well-known 0x0x control chars) using backslash escape sequences.

    remarks
    • Well-known low-ASCII control chars will be escaped using simple \, e.g. 0x0a => \n
    • Non-BMP chars will be escaped using \Uxxxxxxxx
    • Chars outside 0x20 - 0x7e range will be escaped using \uxxxxx

    Parameters

    • src: string

    Returns string

Const float

  • float(prec: number, special?: boolean): Stringer<number>
  • Returns Stringer which formats numbers to given precision. If special is true, then exceptional handling for:

    • NaN => "NaN"
    • Infinity => "+/-∞"

    Parameters

    • prec: number
    • Optional special: boolean

      true, if special handling for NaN/Infinity values

    Returns Stringer<number>

Const floatFixedWidth

  • floatFixedWidth(width: number, prec?: number): Stringer<number>
  • Similar to float, returns Stringer which formats numbers to given character width & precision. Uses scientific notation if needed.

    Default precision: 3 fractional digits

    Parameters

    • width: number
    • Optional prec: number

    Returns Stringer<number>

Const format

  • format(fmt: any[], ...args: any[]): string
  • Parameters

    • fmt: any[]
    • Rest ...args: any[]

    Returns string

Const grams

  • grams(x: number, ...xs: any[]): string
  • Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const grid

  • grid(cols: number, rows: number, w: number, h: number, __namedParameters?: string): string
  • Returns a grid of given cols x rows as string, each cell of size w x h. The optional chars can be used to customize the grid.

    example
    console.log(grid(3, 3, 4, 2));
    // +---+---+---+
    // |   |   |   |
    // +---+---+---+
    // |   |   |   |
    // +---+---+---+
    // |   |   |   |
    // +---+---+---+
    
    console.log(grid(3, 3, 4, 2, "*_/"));
    // *___*___*___*
    // /   /   /   /
    // *___*___*___*
    // /   /   /   /
    // *___*___*___*
    // /   /   /   /
    // *___*___*___*
    
    console.log(grid(3, 2, 3, 3, "+  #"));
    // +  +  +
    //  ## ##
    //  ## ##
    // +  +  +
    //  ## ##
    //  ## ##
    // +  +  +
    

    Parameters

    • cols: number
    • rows: number
    • w: number
    • h: number
    • __namedParameters: string = "+-| "

    Returns string

Const hstr

  • hstr(x: any, ...xs: any[]): string

Const ignore

  • ignore(_: any): string
  • Helper for format which ignores argument and always returns an empty string.

    Parameters

    • _: any

    Returns string

Const int

  • int(x: number, ...xs: any[]): string
  • Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const intLocale

  • intLocale(locale?: string): Stringer<number>

Const interpolate

  • interpolate(src: string, ...args: any[]): string
  • Takes a string template with embedded {number} style terms and any number of args. Replaces numbered terms with their respective args given.

    example
    interpolate("let {0}: {2} = {1};", "a", 42, "number")
    // "let a: number = 42;"
    

    Parameters

    • src: string
    • Rest ...args: any[]

    Returns string

Const interpolateKeys

  • interpolateKeys(src: string, keys: IObjectOf<NumOrString>): string
  • Similar to interpolate, but uses alphanumeric placeholders in the template string and an object of values for the stated keys.

    example
    interpolateKeys(
      "let {id}: {type} = {val};",
      { id: "a", type: "number", val: 42 }
    )
    // "let a: number = 42;"
    

    Parameters

    • src: string
    • keys: IObjectOf<NumOrString>

    Returns string

Const isAnsi

  • isAnsi(x: string): boolean
  • Returns true iff x contains ANSI control sequences.

    Parameters

    • x: string

    Returns boolean

Const isAnsiEnd

  • isAnsiEnd(x: string): boolean
  • Returns true iff x ends w/ an ANSI control sequence.

    Parameters

    • x: string

    Returns boolean

Const isAnsiStart

  • isAnsiStart(x: string): boolean
  • Returns true iff x starts w/ an ANSI control sequence.

    Parameters

    • x: string

    Returns boolean

Const join

  • Higher-order version of Array.join(). Takes separator string sep and returns function which accepts an array and joins all elements w/ separator into a result string.

    example
    const slashes = join("/");
    
    slashes([1, 2, 3]);
    // "1/2/3"
    
    const formatOBJFace = partial(
      format, ["f ", slashes, " ", slashes, " ", slashes]
    );
    
    formatOBJFace([1, 2], [3, 4], [5, 6]);
    // "f 1/2 3/4 5/6"
    

    Parameters

    • x: string

    Returns Stringer<any[]>

Const kebab

  • kebab(x: string, ...xs: any[]): string
  • Converts a CamelCase string into kebab case, with optional custom delimiter (- by default).

    example
    kebab("FooBar23Baz");
    // "foo-bar23-baz"
    

    Parameters

    • x: string

      -

    • Rest ...xs: any[]

    Returns string

Const lengthAnsi

  • lengthAnsi(x: string): number
  • Returns length of x excluding any ANSI control sequences (via stripAnsi).

    Parameters

    • x: string

    Returns number

Const lower

  • lower(a: string): string
  • Lowercase string formatter.

    Parameters

    • a: string

    Returns string

Const maybeParseFloat

  • maybeParseFloat(x: string, defaultVal?: any): any
  • Parameters

    • x: string
    • defaultVal: any = 0

    Returns any

Const maybeParseInt

  • maybeParseInt(x: string, defaultVal?: any, radix?: number): any
  • Parameters

    • x: string
    • defaultVal: any = 0
    • radix: number = 10

    Returns any

Const meters

  • meters(x: number, ...xs: any[]): string
  • Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const padLeft

  • padLeft(n: number, ch?: string | number): (x: any, length?: number) => string
  • Parameters

    • n: number

      target length

    • Optional ch: string | number

      pad character(s)

    Returns (x: any, length?: number) => string

      • (x: any, length?: number): string
      • Parameters

        • x: any
        • Optional length: number

        Returns string

Const padRight

  • padRight(n: number, ch?: string | number): (x: any, length?: number) => string
  • Parameters

    • n: number

      target length

    • Optional ch: string | number

      pad character(s)

    Returns (x: any, length?: number) => string

      • (x: any, length?: number): string
      • Parameters

        • x: any
        • Optional length: number

        Returns string

Const percent

  • percent(prec?: number): Stringer<number>
  • Returns Stringer which formats given fractions as percentage (e.g. 0.1234 => 12.34%).

    Parameters

    • prec: number = 0

      number of fractional digits (default: 0)

    Returns Stringer<number>

Const radix

  • radix(radix: number, len: number, prefix?: string): Stringer<number>
  • Returns a Stringer which formats given numbers to radix, len and with optional prefix (not included in len).

    remarks

    Only bases 2 - 36 are supported, due to native Number.toString() limitations.

    Parameters

    • radix: number

      -

    • len: number

      -

    • Optional prefix: string

      -

    Returns Stringer<number>

Const repeat

  • repeat(a: string, b: number): string
  • Parameters

    • a: string
    • b: number

    Returns string

Const ruler

  • ruler(width: number, major?: number, a?: string, b?: string): string
  • Returns a ruler-like string of given width, using a character for major ticks and b for minor ticks.

    example
    console.log(ruler(40))
    // |''''|''''|''''|''''|''''|''''|''''|''''
    
    console.log(ruler(40, 8, "!", "."))
    // !.......!.......!.......!.......!.......
    

    Parameters

    • width: number
    • major: number = 5
    • a: string = "|"
    • b: string = "'"

    Returns string

Const seconds

  • seconds(x: number, ...xs: any[]): string
  • Parameters

    • x: number
    • Rest ...xs: any[]

    Returns string

Const slugify

  • slugify(x: string, ...xs: any[]): string

Const slugifyGH

  • slugifyGH(str: string): string
  • Similar to slugify, however uses GitHub's anchor naming rules for headings in markdown files (AFAICT).

    example
    slugifyGH("Me, myself (& ëye)!")
    // "me-myself--ëye"
    

    Parameters

    • str: string

    Returns string

Const snake

  • snake(a: string): string
  • Short for kebab using _ as delimiter.

    Parameters

    • a: string

    Returns string

Const spacesToTabs

  • spacesToTabs(src: string, tabSize?: number): string

Const spacesToTabsLine

  • spacesToTabsLine(line: string, tabSize?: number): string
  • Takes a single line string and converts all tab characters to spaces, using given tabSize. Inverse op of tabsToSpacesLine.

    Parameters

    • line: string
    • tabSize: number = 4

    Returns string

Const splice

  • splice(src: string, insert: string, from: number, to?: number): string
  • Forms a new strings which inserts given insert string into src string at from position and appends remaining src chars from original to position. If from and to are equal (to by default is), the operation is a pure insertion. If not, then some chars from src will be removed in the new string. If either position is negative, it'll be considered relative to the end of the src.

    Parameters

    • src: string

      -

    • insert: string

      -

    • from: number

      -

    • to: number = ...

      -

    Returns string

split

  • split(src: string, delim?: RegExp | string, includeDelim?: boolean): Generator<string, void, unknown>
  • Iterator version of String.prototype.split(). Yields iterable of substrings of src, delimited by given regexp (default: unix & windows linebreaks).

    remarks

    Use this function to avoid creating an entire full copy of the original source string, e.g. when only single-token or line-based accesses are needed. This function is ~2x faster for large strings (benchmarked with 8MB & 16MB inputs), with dramatically lower memory consumption.

    Parameters

    • src: string
    • delim: RegExp | string = ...
    • includeDelim: boolean = false

    Returns Generator<string, void, unknown>

Const str

  • str(x: any): string
  • Helper for format which coerces x to a string.

    Parameters

    • x: any

    Returns string

Const stringify

  • stringify(all?: boolean, indent?: number): Stringer<any>
  • Higher order version of JSON.stringify() with the option to treat strings and numbers differently. If all is false (default), strings and numbers are simply converted using String(x). If indent is given, it will be used for JSON.stringify(x, null, indent)

    Parameters

    • all: boolean = false
    • Optional indent: number

    Returns Stringer<any>

Const stripAnsi

  • stripAnsi(x: string): string
  • Removes all ANSI control sequences from given string.

    example
    stripAnsi("\x1B[32mhello\x1B[0m \x1B[91mworld\x1B[0m!"");
    // 'hello world!'
    

    Parameters

    • x: string

    Returns string

Const tabsToSpaces

  • tabsToSpaces(src: string, tabSize?: number): string
  • Multi-line version of tabsToSpacesLine.

    example
    console.log(
      tabsToSpaces("0\t1\t2", 10)
      + "\n" +
      tabsToSpaces("0\t45\t890\t\t6\t0")
      + "\n" +
      tabsToSpaces("^\t^\t^\t^\t^\t^")
    );
    // 0         1         2
    // 0   45  890     6   0
    // ^   ^   ^   ^   ^   ^
    

    Parameters

    • src: string
    • tabSize: number = 4

    Returns string

Const tabsToSpacesLine

  • tabsToSpacesLine(line: string, tabSize?: number): string
  • Takes a single line string and converts all tab characters to spaces, using given tabSize.

    Parameters

    • line: string
    • tabSize: number = 4

    Returns string

Const trim

  • Higher order trim function (both sides) with support for user defined trimmable characters (default: whitespace only).

    example
    trim()("  Hello   ")
    // "Hello"
    
    trim(" -+")("-+-+- Hello -+-+-")
    // "Hello"
    

    Parameters

    • x: string

    Returns Stringer<string>

Const truncate

  • truncate(n: number, suffix?: string): Stringer<string>

Const truncateLeft

  • truncateLeft(n: number, prefix?: string): Stringer<string>

Const truncateRight

  • truncateRight(n: number, suffix?: string): Stringer<string>

Const unescape

  • unescape(src: string): string

Const units

  • units(exp: UnitDefs, base: string, prec?: number): Stringer<number>
  • Parameters

    • exp: UnitDefs
    • base: string
    • Optional prec: number

    Returns Stringer<number>

Const upper

  • upper(a: string): string
  • Uppercase string formatter.

    Parameters

    • a: string

    Returns string

Const upperSnake

  • upperSnake(a: string): string
  • Uppercase version of snake.

    Parameters

    • a: string

    Returns string

Const uuid

  • uuid(id: ArrayLike<number>, i?: number): string
  • Same as uuid. Returns UUID formatted string of given byte array from optional start index i (default: 0). Array must have min. length 16.

    remarks

    Use uuid to also generate an UUID from scratch (rather than just format one).

    Parameters

    • id: ArrayLike<number>

      -

    • Optional i: number

      -

    Returns string

Const vector

  • vector(size: number, prec?: number | Stringer<number>, delim?: string, pre?: string, post?: string): Stringer<ArrayLike<number>>
  • Higher order formatter for n-D vectors, with each element formatted using prec and using optional delimiter and pre/postfixes.

    size
    • vector size (optimized for size 1-4)
    prec
    • precision (see float) or existing number formatter
    delim
    • delimiter (default: ,)
    pre
    • prefix (default: [)
    post
    • prefix (default: ])

    Parameters

    • size: number
    • Optional prec: number | Stringer<number>
    • Optional delim: string
    • Optional pre: string
    • Optional post: string

    Returns Stringer<ArrayLike<number>>

Const wordWrap

Const wordWrapLine

  • wordWrapLine(line: string, opts: Partial<WordWrapOpts>, acc?: Line[]): Line[]
  • Wordwraps a single-line string using provided options. Returns array of {@link Line} objects, which can simply be .join("\n")ed to convert back into text.

    see

    wordWrap for main user facing alternative.

    internal

    Parameters

    Returns Line[]

Const wordWrapLines

  • wordWrapLines(lines: string, opts: Partial<WordWrapOpts>): Line[]
  • Wordwraps a multi-line string using provided options. Returns array of {@link Line} objects, which can simply be .join("\n")ed to convert back into text.

    see

    wordWrap for main user facing alternative.

    Parameters

    Returns Line[]

Const wrap

  • Returns a Stringer which wrap inputs with given pad string on both sides.

    Parameters

    • pad: string

    Returns Stringer<any>

Generated using TypeDoc