← Back to all snippets
JAVASCRIPT

Extract All Numeric Digits from Text

Discover how to extract all contiguous numeric digits from any string using JavaScript's `match` method with a global regular expression. Useful for data parsing and cleaning.

function extractNumbers(text) {
  const numberRegex = /\d+/g;
  return text.match(numberRegex) || [];
}

// Examples
console.log(extractNumbers("My phone number is 123-456-7890. The year is 2023.")); // ["123", "456", "7890", "2023"]
console.log(extractNumbers("No numbers here!")); // []
console.log(extractNumbers("Item costs $99.99 and weighs 10kg.")); // ["99", "99", "10"]
How it works: This snippet defines a JavaScript function that extracts all sequences of one or more digits from a given string. It uses the `\d+` pattern to match numbers and the `g` flag for a global search, returning an array of all matches. This is ideal for extracting numerical data from unstructured text.

Need help integrating this into your project?

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

Hire DigitalCodeLabs