0
0
JavascriptHow-ToBeginner · 3 min read

How to Extract Numbers from String in JavaScript Easily

To extract numbers from a string in JavaScript, use the match() method with a regular expression like /\d+/g to find all digit sequences. This returns an array of number strings, which you can convert to numbers using map(Number).
📐

Syntax

The main syntax to extract numbers from a string uses the match() method with a regular expression:

  • string.match(/\d+/g): Finds all groups of digits in the string.
  • /\d+/g: The regular expression where \d+ means one or more digits, and g means global search (find all matches).
  • The result is an array of strings representing numbers found.

You can then convert these strings to actual numbers using map(Number).

javascript
const numbers = string.match(/\d+/g);
const numericValues = numbers ? numbers.map(Number) : [];
💻

Example

This example shows how to extract all numbers from a string and convert them to actual numbers.

javascript
const text = "I have 2 apples and 15 oranges.";
const numbers = text.match(/\d+/g);
const numericValues = numbers ? numbers.map(Number) : [];
console.log(numericValues);
Output
[2, 15]
⚠️

Common Pitfalls

One common mistake is forgetting that match() returns strings, not numbers. You must convert them explicitly. Also, if no numbers exist, match() returns null, so you should check for that to avoid errors.

Another pitfall is using parseInt() on the whole string, which only extracts the first number and ignores the rest.

javascript
const text = "No numbers here.";
const numbers = text.match(/\d+/g);
// Wrong: This will cause error if numbers is null
// const numericValues = numbers.map(Number);

// Right way:
const numericValues = numbers ? numbers.map(Number) : [];
console.log(numericValues);
Output
[]
📊

Quick Reference

MethodDescriptionExample
string.match(/\d+/g)Finds all digit groups as strings"abc123def456" → ["123", "456"]
map(Number)Converts string array to numbers["123", "456"].map(Number) → [123, 456]
parseInt(string)Extracts first number onlyparseInt("123abc456") → 123
Check for nullAvoid errors if no numbers foundif (numbers) { ... } else { ... }

Key Takeaways

Use string.match(/\d+/g) to find all numbers as strings in a string.
Convert matched strings to numbers with map(Number) for numeric use.
Always check if match() returns null before mapping to avoid errors.
parseInt() extracts only the first number, not all numbers.
Regular expressions are a simple and powerful way to extract numbers.