Parse everyday height and weight text into structured data

A JavaScript and TypeScript library for health apps, fitness trackers and web forms. It reads metric and imperial units, and numbers in digits or in words, as in 5' 11" or five feet eleven inches.A JavaScript and TypeScript library for input like 5' 11" or five feet eleven inches.

npm install @afahy/fluent-measures@0.3.0
parseMeasurement(input, options)
5' 11" type: 'height', normalizedUnit: 'cm'
180.34 cm
eighty kilograms type: 'weight'
80 kg
5 foots 10 inc fuzzy: true
70 in
not a measurement no options
null
150 lbs type: 'weight', normalizedUnit: 'kg'
68.0388555 kg
five foot ten type: 'height'
70 in
72,5 kg no options
72.5 kg
150-180 lbs no options
null
Results show value and unit. Additional examples appear above this button.
  • Metric and imperial: ft, in, cm, m, lb and kg; convert with normalizedUnit.

  • Flexible input: Digits or words, thousands separators and decimal commas; allow a unit typo with fuzzy.

Install

Add the package with your package manager.

npm

npm install @afahy/fluent-measures@0.3.0

yarn

yarn add @afahy/fluent-measures@0.3.0

pnpm

pnpm add @afahy/fluent-measures@0.3.0

Small footprint. No runtime dependencies. At most 6.0 kB for ESM and 6.0 kB for CommonJS, minified and compressed with Brotli.

Quick start

Import parseMeasurement with ES modules or CommonJS, pass it the text to read, and check the result before you use it. The unit in the text identifies a height or weight, so these inputs need no options.

ES modules

import { parseMeasurement } from '@afahy/fluent-measures';

const result = parseMeasurement('6 ft');
/* ✓ Returns:
{
  value: 6,
  unit: 'ft',
  type: 'height',
  matches: [
    { value: 6, unit: 'ft' }
  ],
  raw: '6 ft'
}
*/
if (result) {
  console.log(result);
}
import {
  parseMeasurement,
} from '@afahy/fluent-measures';

const result =
  parseMeasurement('6 ft');
if (result) {
  console.log(result);
}

CommonJS

const { parseMeasurement } = require('@afahy/fluent-measures');

const result = parseMeasurement('6 ft');
if (result) {
  console.log(result);
}
const {
  parseMeasurement,
} = require(
  '@afahy/fluent-measures',
);

const result =
  parseMeasurement('6 ft');
if (result) {
  console.log(result);
}
Returns

result6 fta height

value and unit describe the measurement, type identifies height or weight, matches lists the parts found, and raw keeps the original text.

When the text holds no measurement, result is null. The if (result) guard above checks before using it.

150 lbs
150 lb
not a measurement
null

Usage

Adapt the parser to your field: restrict its type, convert the result, accept a number without a unit, or allow spelling errors.

Choose a task

Read only one type

Set type when a field expects one kind of measurement, such as a weight. The parser then reads only that kind, so a height typed into a weight field returns null. Use type: 'height' for a height field.

TypeScript
const accepted = parseMeasurement(
  'eighty kilograms',
  { type: 'weight' },
);
/* ✓ Returns:
{
  value: 80,
  unit: 'kg',
  type: 'weight',
  matches: [
    { value: 80, unit: 'kg' }
  ],
  raw: 'eighty kilograms'
}
*/

const rejected = parseMeasurement('6 ft', { type: 'weight' });
/* ✓ Returns: null */
const accepted = parseMeasurement(
  'eighty kilograms',
  { type: 'weight' },
);

const rejected = parseMeasurement(
  '6 ft',
  { type: 'weight' },
);
Returns

accepted80 kga weight

rejectednulla height in a weight field

Convert to one unit

Set normalizedUnit to get the result in the unit that you store. The compound height below combines 5 ft and 11 in: (5 × 12 + 11) × 2.54 = 180.34 cm. matches keeps the original parts in their own units.

Height conversion

parseMeasurement('5\' 11"', { type: 'height', normalizedUnit: 'cm' });
/* ✓ Returns:
{
  value: 180.34,
  unit: 'cm',
  type: 'height',
  matches: [
    { value: 5, unit: 'ft' },
    { value: 11, unit: 'in' }
  ],
  raw: '5\' 11"'
}
*/
parseMeasurement('5\' 11"', {
  type: 'height',
  normalizedUnit: 'cm',
});
Returns

180.34 cmmatches: 5 ft and 11 in

Weight conversion

parseMeasurement('150 lbs', { type: 'weight', normalizedUnit: 'kg' });
/* ✓ Returns:
{
  value: 68.0388555,
  unit: 'kg',
  type: 'weight',
  matches: [
    { value: 150, unit: 'lb' }
  ],
  raw: '150 lbs'
}
*/
parseMeasurement('150 lbs', {
  type: 'weight',
  normalizedUnit: 'kg',
});
Returns

68.0388555 kgmatches: 150 lb

Without conversion, feet and inches combine into inches. Written-out numbers work too:

five foot ten{ type: 'height' }
70 in

matches keeps 5 ft and 10 in, just as it keeps the parts above.

Numbers without a unit

People sometimes type only a number, for example in a calculator field labeled “Height (in)”. Set defaultUnit to that source unit. Written units take precedence. normalizedUnit chooses the output unit and measurement type; it never supplies a source unit. There is no magnitude guessing: 1.8 with a centimeter default means 1.8 cm.

TypeScript
parseMeasurement('72', {
  defaultUnit: 'in',
});
/* ✓ Returns:
{
  value: 72,
  unit: 'in',
  type: 'height',
  matches: [
    { value: 72, unit: 'in' }
  ],
  raw: '72'
}
*/
Returns

72 insource default: inches

Spelling errors in units

Set fuzzy: true to read a unit name that has one spelling error. Without it, a unit name must be exact, so the same text returns null. One letter added, removed or changed is one error. An ordinary word one letter from a unit name, such as feat, reads as that unit too. Limits says what fuzzy matching can get wrong.

TypeScript
// With fuzzy matching
const result = parseMeasurement('5 foots 10 inc', { fuzzy: true });
/* ✓ Returns:
{
  value: 70,
  unit: 'in',
  type: 'height',
  matches: [
    { value: 5, unit: 'ft' },
    { value: 10, unit: 'in' }
  ],
  raw: '5 foots 10 inc'
}
*/

// Without it
const strict = parseMeasurement('5 foots 10 inc');
/* ✓ Returns: null */
// With fuzzy matching
const result = parseMeasurement(
  '5 foots 10 inc',
  { fuzzy: true },
);

// Without it
const strict = parseMeasurement(
  '5 foots 10 inc',
);
Returns

result70 inunit names read with errors

strictnullunit names must be exact

API

The package exports one function, parseMeasurement, and the ParseOptions, ParsedValue, Unit and MeasurementType types.

parseMeasurement

Reads one height or weight from a string. When it returns null, Troubleshooting lists the causes to look for, including input longer than maxLength. For string input it validates options before length or text: the options object, maxLength, type, normalizedUnit, defaultUnit, retired options, then dimension conflicts. Invalid options throw even for empty or overlong strings. Non-string runtime input returns null before reading options. Empty strings and null values for type or normalizedUnit count as absent.

To migrate, remove allowUnqualified and inferUnit; either throws when defined, including false. An explicitly undefined property is absent. Use defaultUnit: 'in' or 'lb' for imperial fields, 'kg' for metric weight, and choose 'm' or 'cm' explicitly for metric height. fuzziness is retired too: any defined value throws. Replace fuzziness: 1 or 2 with fuzzy: true, which reads one spelling error.

function parseMeasurement(input: string, options?: ParseOptions): ParsedValue | nullfunction parseMeasurement(input: string,options?: ParseOptions,): ParsedValue | null

inputstring
The text to read, for example "6 ft", "150 lbs" or "180 cm".
options?ParseOptions
Optional settings.

ParseOptions

interface ParseOptions

type?MeasurementType
Purpose
The measurement type to read. See Read only one type.
When omitted
Selected by normalizedUnit when set; otherwise by written units or defaultUnit for a bare number.
Constraints
'height' or 'weight'. Must agree with normalizedUnit.
normalizedUnit?Unit
Purpose
The unit of the result. See Convert to one unit.
When omitted
Uses the written or default source unit.
Constraints
Also selects the measurement type, so a weight unit reads only a weight. A type that contradicts it throws an error. Shorthand such as 5-11 still needs type. This option never supplies a source unit for a bare number.
fuzzy?boolean
Purpose
Read a unit name with one spelling error. See Spelling errors in units.
Default
false — unit names must be exact.
Constraints
true or false. Other values throw.
defaultUnit?Unit
Purpose
Source unit for one complete unwrapped number, including supported fractions and number words. See Numbers without a unit.
When omitted
Bare numbers return null.
Constraints
One of the six canonical units. Written units win. Must agree with the dimension selected by type or normalizedUnit, if supplied. No magnitude guessing or discarded wrappers or text.
maxLength?number
Purpose
The largest raw input.length before trimming or parsing.
Default
1000.
Constraints
A number of at least 1, or Infinity for no limit. Other values throw.

ParsedValue

interface ParsedValue

valuenumber
The value of the measurement.
unitUnit | null
The unit of the value.
typeMeasurementType
The measurement type: 'height' or 'weight'.
matchesArray<{ value: number; unit: Unit | null }>
Each part of the measurement in its unit from the text, as 5 ft and 11 in for 5' 11".
rawstring
The input text.

Unit

type Unit = 'ft' | 'in' | 'cm' | 'm' | 'lb' | 'kg'type Unit =| 'ft' | 'in' | 'cm' | 'm'| 'lb' | 'kg'

The canonical unit names. Input can use other spellings; see Supported units for the accepted aliases.

MeasurementType

type MeasurementType = 'height' | 'weight'type MeasurementType ='height' | 'weight'

The kind of measurement. Used by ParseOptions.type and ParsedValue.type.

Supported units

Input can use any spelling listed here. Results always use the short unit name.

Unit System Also accepts
Height
ft Imperial
  • feet
  • foot
  • 'feet mark
in Imperial
  • inch
  • inches
  • "inch mark
cm Metric
  • cms
  • centimeter
  • centimeters
  • centimetre
  • centimetres
m Metric
  • meter
  • meters
  • metre
  • metres
Weight
lb Imperial
  • lbs
  • pound
  • pounds
  • #directly after a number, as in 185#
kg Metric
  • kgs
  • kilo
  • kilos
  • kilogram
  • kilograms
  • kilogramme
  • kilogrammes

Most units can also come before their number, as in kg 70. The short forms in and m can come first only as a label, because before a number they are usually ordinary words. PARSING.md says what counts as a label.

Limits

Some text returns null, or a result that you might not expect.

Input Result
12st 4lb
nullStone, ounces and grams aren't supported
150-180 lbs
nullA range isn't one measurement
70 kg (154 lbs)
nullTwo weights, even when they agree
210 lbs to 180 lbs
nullA range is not one measurement

The whole entry must be one complete measurement, including supported compounds such as 5 ft 11 in. Two heights or two weights return null, even when they agree. For exactly one complete height and one complete weight, set type or normalizedUnit to select one. Both expressions must be valid; without a selector the result is null.

Only a few words may surround a measurement

I'm five foot eleven tall and about 180 cm are supported. Unrelated prose is not: Top 10 in the class returns null. Quotation marks and brackets around the entry or a number are not supported either: (180 cm) returns null. Fuzzy matching does not discard leftover text, but with fuzzy: true an ordinary word one letter from a unit name reads as that unit, before or after a number: 6 food returns 6 ft.

PARSING.md gives all the rules, with examples.

Troubleshooting

If parseMeasurement returns null, look for these causes:

  1. The unit isn't supported. See Supported units.
  2. The text doesn't say whether it is a height or a weight. Set type.
  3. A number has no unit. Set defaultUnit to the source unit shown by the field.
  4. A unit name has a spelling error. Set fuzzy: true to read one error.
  5. The text has a range, duplicate measurements, an incomplete fragment or unsupported text. See Limits.
  6. The input isn't a string. Non-string input returns null at runtime; the TypeScript parameter remains string.
  7. The raw input.length, before trimming, exceeds maxLength (default 1,000). Set a larger maxLength or Infinity for no limit. Length counts UTF-16 code units, as JavaScript does.

If none of these explains the result, search the GitHub issues. To report a bug, open an issue with the input, the options and the result that you expected.

Docs for your version

Results can change between versions. To find the version that your app uses, run npm ls @afahy/fluent-measures. Each verified npm release has its own docs page:

See the list of verified versions. The docs for a version are at versions/<version>/ on this site.

Versions 0.1.0 and 0.1.1 have no docs page. Use the README in your installed package.

Edit this page on GitHub