Skip to content

extractNumber function ​

Extracts the first number of a text, with . or , before the decimals: 1,234 is 1.234.

ts
import { extractNumber } from 'utils';

Signature ​

ts
export function extractNumber(input: string): number | undefined

Parameters ​

NameDescription
inputA text, such as a label or a sensor message.

Returns ​

The first number; undefined when there is none.

Example ​

ts
extractNumber('Speed: -12,5 kn'); // -12.5
extractNumber('n/a'); // undefined

Tests ​

Line coverage: 100 %.

  • ✅ extracts "42" as 42
  • ✅ extracts "Speed: -12,5 kn" as -12.5
  • ✅ extracts "heading 270.5°" as 270.5
  • ✅ extracts "+3" as 3
  • ✅ extracts "value .5" as 0.5
  • ✅ extracts "1,234" as 1.234
  • ✅ extracts "a1b2" as 1
  • ✅ returns undefined for ""
  • ✅ returns undefined for "n/a"
  • ✅ returns undefined for "-"
  • ✅ returns undefined for "."
  • ✅ returns undefined for "abc"

Source ​

src/string/extract-number.ts (on GitHub)

Files it needs ​

src/string/extract-number.ts imports, directly or not:

Source code
ts
import { parseMatchedNumber } from './internal';

const NUMBER_SOURCE = String.raw`[+\-]?(?:\d+(?:[,.]\d+)?|[,.]\d+)`;

const NUMBER_PATTERN = new RegExp(NUMBER_SOURCE, 'v');

/**
 * Extracts the first number of a text, with `.` or `,` before the decimals: `1,234` is `1.234`.
 *
 * @param input - A text, such as a label or a sensor message.
 * @returns The first number; `undefined` when there is none.
 * @example
 * extractNumber('Speed: -12,5 kn'); // -12.5
 * extractNumber('n/a'); // undefined
 */
export function extractNumber(input: string): number | undefined {
  const match = NUMBER_PATTERN.exec(input);
  return match ? parseMatchedNumber(match[0]) : undefined;
}
Test file
ts
import { extractNumber } from './extract-number';

describe(extractNumber, () => {
  it.for([
    ['42', 42],
    ['Speed: -12,5 kn', -12.5],
    ['heading 270.5°', 270.5],
    ['+3', 3],
    ['value .5', 0.5],
    ['1,234', 1.234],
    ['a1b2', 1],
  ] as const)('extracts %j as %s', ([input, expected]) => {
    expect(extractNumber(input)).toBe(expected);
  });

  it.for(['', 'n/a', '-', '.', 'abc'])('returns undefined for %j', (input) => {
    expect(extractNumber(input)).toBeUndefined();
  });
});

Keywords: extract, number, strings, function

Generated from the JSDoc of the sources.