Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab all numbers from a string in JavaScript? [duplicate]

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.

like image 550
Jake Stevens Avatar asked Jan 25 '13 02:01

Jake Stevens


Video Answer


1 Answers

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)
like image 72
Samuel Liew Avatar answered Sep 19 '22 06:09

Samuel Liew