All files / string extract-numbers.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 2/2
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18    1x   1x                     7x    
import { parseMatchedNumber } from './internal';
 
const NUMBER_SOURCE = String.raw`[+\-]?(?:\d+(?:[,.]\d+)?|[,.]\d+)`;
 
const NUMBERS_PATTERN = new RegExp(NUMBER_SOURCE, 'gv');
 
/**
 * Extracts every number of a text, with the rules of `extractNumber`.
 *
 * @param input - A text.
 * @returns The numbers found, in order; empty when there is none.
 * @example
 * extractNumbers('from 1.5 to -3'); // [1.5, -3]
 */
export function extractNumbers(input: string): number[] {
  return Array.from(input.matchAll(NUMBERS_PATTERN), (match) => parseMatchedNumber(match[0]));
}