Skip to content

Class UnitParser

Source: UnitParser.ts

Parses a string that contains a numeric value and a unit name, according to a configurable format pattern and a list of recognized units. Returns the parsed value and the canonical unit name, or null if the input does not match.

Import

ts
import { UnitParser } from '@litert/utils-string';

Constructor

ts
new UnitParser(opts: IUnitParserOptions)

Parameters

Error Handling

  • RangeError — Thrown if opts.units is empty, or if opts.maxDecimalPlaces is negative or non-integer, or if two units share the same alias.
  • SyntaxError — Thrown if opts.format does not contain both {value} and {unit} placeholders.

Properties

NameTypeDescription
formatstringThe format string provided at construction.
unitsReadonlyArray<Readonly<IUnitInfo>>The normalized list of units.
caseInsensitivebooleanWhether unit matching is case-insensitive (default true).
maxDecimalPlacesnumberMaximum decimal places allowed in the value.

Instance Methods

parse

ts
parse(input: string): IUnitParserResult | null;

Attempts to parse input according to the configured format and unit list.

Parameters

  • Parameter input: string

    The string to parse.

Return Value

An IUnitParserResult containing the value (string) and the canonical unit name, or null if the string does not match.

Examples

ts
import { UnitParser } from '@litert/utils-string';

const parser = new UnitParser({
    format: '{value}{unit}',
    units: [
        { name: 'B',   aliases: ['b', 'byte', 'bytes'] },
        { name: 'KiB', aliases: ['kib', 'k'] },
        { name: 'MiB', aliases: ['mib', 'm'] },
        { name: 'GiB', aliases: ['gib', 'g'] },
    ],
    caseInsensitive: true,
});

parser.parse('1.5GiB');  // { value: '1.5', unit: 'GiB' }
parser.parse('10mib');   // { value: '10',  unit: 'MiB' }
parser.parse('512B');    // { value: '512', unit: 'B'   }
parser.parse('5 TB');    // null (space not in format)
parser.parse('xyz');     // null (no match)

Format with space

ts
const parser2 = new UnitParser({
    format: '{value} {unit}',
    units: ['cm', 'm', 'km'],
});

parser2.parse('12.5 km'); // { value: '12.5', unit: 'km' }
parser2.parse('12.5km');  // null (format requires a space)