Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to extract multiple numbers from a string

Input:

"NEW YORK (Reuters) U.S. stock index futures pointed to a slight rebound on Wall Street on Wednesday, with futures for the S&P 500 up 0.34 percent, Dow Jones futures up 0.12 percent and Nasdaq 100 futures up 0.51 percent at 0921 GMT."

Output should be array of all numbers including floats.

A little similar thread but it extracts only one number.

like image 868
understack Avatar asked Dec 10 '22 13:12

understack


2 Answers

this should do it:

var text = "NEW YORK (Reuters) U.S. stock index futures pointed to a slight rebound on Wall Street on Wednesday, with futures for the S&P 500 up 0.34 percent, Dow Jones futures up 0.12 percent and Nasdaq 100 futures up 0.51 percent at 0921 GMT.";
console.log(text.match(/(\d[\d\.]*)/g));

you can filter out the invalid numbers e.g. 55.55.55 with the following code:

var numbers = [];
text.replace(/(\d[\d\.]*)/g, function( x ) { var n = Number(x); if (x == n) { numbers.push(x); }  })
like image 171
KARASZI István Avatar answered Dec 12 '22 02:12

KARASZI István


This regular expression should work:

/[-+]?[0-9]*\.?[0-9]+/g

A test:

"NEW YORK (Reuters) U.S. stock index futures pointed to a slight rebound on Wall Street on Wednesday, with futures for the S&P 500 up 0.34 percent, Dow Jones futures up 0.12 percent and Nasdaq 100 futures up 0.51 percent at 0921 GMT.".match(/[-+]?[0-9]*\.?[0-9]+/g)

returns this Array:

["500", "0.34", "0.12", "100", "0.51", "0921"]
like image 21
Matt Avatar answered Dec 12 '22 01:12

Matt