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.
The numbers may also 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 see it working interactively, provide a text to this Extract Numbers utility app, and get a list of extracted numbers.
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.
In case you are looking for a JavaScript library, it’s available as extract-numbers on NPM. It has no dependency.
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
- SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
- Yup Date Format Validation With Moment JS
- Yup Number Validation: Allow Empty String
- Exactly Same Query Behaving Differently in Mongo Client and Mongoose
- JavaScript Unit Testing JSON Schema Validation
- Reduce JS Size With Constant Strings
- JavaScript SDK