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
Parameter
opts: IUnitParserOptionsConfiguration object. See
IUnitParserOptions.
Error Handling
RangeError— Thrown ifopts.unitsis empty, or ifopts.maxDecimalPlacesis negative or non-integer, or if two units share the same alias.SyntaxError— Thrown ifopts.formatdoes not contain both{value}and{unit}placeholders.
Properties
| Name | Type | Description |
|---|---|---|
format | string | The format string provided at construction. |
units | ReadonlyArray<Readonly<IUnitInfo>> | The normalized list of units. |
caseInsensitive | boolean | Whether unit matching is case-insensitive (default true). |
maxDecimalPlaces | number | Maximum 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: stringThe 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)