4

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.

1
  • 1
    Regular expressions is the way to go Commented Oct 20, 2010 at 11:30

2 Answers 2

9

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); }  })
Sign up to request clarification or add additional context in comments.

Comments

6

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"]

2 Comments

your solution will fail on: "123.45.67 .56" for e.g.
Depending on what you mean by "fail". It'd return ["123.45", ".67", ".56"]. "123.45.67" is not a float. You might also say it'd fail on 1 000 000 or 1,000,000 - it just depends on what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.