Steffan A. Cline said:
I'm choking on figuring out the correct regexp to extract floats from a
string and then putting that into parseFloat().
parseFloat(somestring.replace(new RegExp("(\\s*\\s*)+?", "gi" ),"");
Extract floats or just one float?
Or remove everything non-floaty from the string?
Depends on which float formats you want to accept.
Before writing a regexp, it's always a good idea to describe, in words,
what it is going to match (and not match).
Let's say that floats are any sequence of digits, optionally containing
at most one decimal point, '.', which must not be at the end of the float.
Then a regexp to find that would be:
var float_re = /(\d*\.)?\d+/g;
You can extract the floats from a string by repeated application of exec:
var match;
while((match = float_re.exec(string))) {
alert("Float found: " + parseFloat(match[0]));
}
or all of them in one go, using match:
var floatStrings = string.match(float_re);
for (var i = 0; i < floatStrings.length; i++) {
alert("Float found: " + parseFloat(floatStrings[i));
}
/L