JAVASCRIPT
Extract All Numbers (Integers & Floats) from a String
Learn to extract both integer and floating-point numbers from a text string using a versatile JavaScript regular expression pattern and convert them to numeric types.
function extractNumbers(text) {
// Matches integers or floating-point numbers.
// Numbers can start with an optional sign (- or +).
// Uses `parseFloat` to convert matched strings to actual numbers.
const numberRegex = /[-+]?\b\d+(\.\d+)?\b/g;
const matches = text.match(numberRegex);
return matches ? matches.map(parseFloat) : [];
}
const dataText = "The price is $12.99, quantity is 5, discount -0.5 and total 100.00. Another value: +30.";
console.log(`Original text: "${dataText}"`);
console.log(`Extracted numbers: ${extractNumbers(dataText)}`);
const noNumbers = "No numbers in this string.";
console.log(`Original text: "${noNumbers}"`);
console.log(`Extracted numbers: ${extractNumbers(noNumbers)}`);
const mixedNumbers = "Item A: 10, Item B: 20.5, Item C: -3.14, Item D: .5 (not captured as full number here).";
console.log(`Original text: "${mixedNumbers}"`);
console.log(`Extracted numbers: ${extractNumbers(mixedNumbers)}`);
How it works: The `extractNumbers` function uses the regex `[-+]?\b\d+(\.\d+)?\b/g` to find all integer and floating-point numbers within a string. The `[-+]?` part optionally matches a leading plus or minus sign. `\b` asserts a word boundary, ensuring whole numbers are matched. `\d+` matches one or more digits, and `(\.\d+)?` optionally matches a decimal point followed by one or more digits. The `g` flag ensures all matches are found. `text.match()` returns an array of matched strings, which are then converted to actual numbers using `parseFloat`.