How to Extract Numbers From a String in JavaScript

Including Decimals, Negatives, and Numbers With Commas.

I'm open to new opportunities! For a full-time role, contract position, or freelance work, reach out at talha@talhaawan.net or LinkedIn.

While working on certain tasks with JavaScript, such as web scraping, 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.

You can use npm logoextract-numbers library to extract numbers from text in your JavaScript code.

For Python code, you can use pypi logo extract-numbers. I have explained the Python version at how to extract numbers from a string in Python.


Valid Numbers

The numbers could be:

  • decimal - examples: average, price, score.

  • negative - examples: temperature, mathematical calculations.

  • comma-separated - example: large amounts such as appear in telephone numbers or bank statements.

Or a combination of any of these.

For example, a simple short text such as:

The World Population at the start of 2023 is 8,009,975,957. It crossed 8 billion mark in 2022.

should return:

[
  "2023",
  "8,009,975,957",
  "8",
  "2022"
]

or in number form (without string/commas):

[
  2023,
  8009975957,
  8,
  2022
]

To get all the possible numbers out of the string requires a regex. And I’ve found one that addresses most of the above cases, plus their combinations.

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

When you purchase through links on techighness.com, I may earn an affiliate commission.
We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. More info cookie script