JAVASCRIPT

Extract All Numeric Values from a String

Learn how to use a regular expression in JavaScript to efficiently extract all numeric sequences (integers or decimals) from any given text string.

function extractNumbers(text) {
  const numberRegex = /\b\d+(\.\d+)?\b/g; // Matches whole numbers and decimals
  const matches = text.match(numberRegex);
  return matches ? matches.map(Number) : [];
}

// Example
const text = "The price is $12.99, quantity 5, discount 0.5 and total 64.95. No other numbers here.";
console.log(extractNumbers(text)); // [12.99, 5, 0.5, 64.95]
How it works: This JavaScript function `extractNumbers` utilizes a regular expression to find and extract all sequences of digits, including optional decimal parts, from a string. The `g` flag ensures all matches are found, and `\b` ensures whole word boundaries. The extracted strings are then converted to actual numbers.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs