How to Extract Numbers From A String In JavaScript

Including decimals, negatives, and numbers with commas

While working on certain tasks with JavaScript, we might need to extract specific data from a string, such as uppercase words or numbers. In this post, I am going to address numbers.

The numbers may also be:

  • decimal - examples: average, price, score
  • negative - examples: temperature, mathematical calculations
  • comma separated - example: large amount such as appear in telephone numbers or bank statement

Or a combination of any of these.

To get them all out of the string requires a regex. I did manage to find one that addressed most of the above cases plus their combinations.

In case you are looking for a JavaScript library, it’s available as extract-numbers on NPM. It has no dependency.

Interactive Example

Modify the textarea below to see the changing results

Results Converted To Number

The Regex And The Code

Regex

  /(-\d+|\d+)(,\d+)*(\.\d+)*/g

Code

const extractNumbers = (text, options) => {
  let numbers;
  if (!text || typeof text !== 'string') {
    return [];
  }

  numbers = text.match(/(-\d+|\d+)(,\d+)*(\.\d+)*/g);

  return numbers;
};

Code To Optionally Convert The Resultant Strings To Numbers

Change the method call to extractNumbers(str, {string: false});, and replace the function code with:

const extractNumbers = (text, options) => {
  let numbers;
  options = options || {};
  if (!text || typeof text !== 'string') {
  return [];
  }

  numbers = text.match(/(-\d+|\d+)(,\d+)*(\.\d+)*/g);

  if (options.string === false) {
  numbers = numbers.map(n => Number(n.replace(/,/g, '')));
  }

  return numbers;
};

See also