8

Let's say I have an input field and want to parse all of the numbers from the submitted string. For example, it could be:

Hi I'm 12 years old.

How do I parse all of the numbers without having a common pattern to work with?

I tried:

x.match(/\d+/)

but it only grabs the 12 and won't go past the next space, which is problematic if the user inputs more numbers with spaces in-between them.

Ben Carp
  • 24,214
  • 9
  • 60
  • 72
Jake Stevens
  • 157
  • 4
  • 13

2 Answers2

12

Add the g flag to return all matches in an array:

var matches = x.match(/\d+/g)

However, this may not catch numbers with seperators, like 1,000 or 0.123

You may want to update your regex to:

x.match(/[0-9 , \.]+/g)
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
1
var words = sentence.split(" ");
var numbers = words.filter(function(w) {
    return w.match(/\d+/);
})
7zark7
  • 10,015
  • 5
  • 39
  • 54