how to extract floating numbers from strings in javascript
You can always load the string into jQuery and get the attributes:
$('<tag value="20.434" value1="-12.334" />').attr('value')
$('<tag value="20.434" value1="-12.334" />').attr('value1')
In your case regex is probably the better route.
You can use the regex /[+-]?\d+(\.\d+)?/g
in conjunction with String.match()
to parse the numbers and Array.map()
to turn them into floats:
var regex = /[+-]?\d+(\.\d+)?/g;
var str = '<tag value="20.434" value1="-12.334" />';
var floats = str.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats);
var str2 = '20.434 -12.334';
var floats2 = str2.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats2);
var strWithInt = "200px";
var ints = strWithInt.match(regex).map(function(v) { return parseFloat(v); });
console.log(ints);
See demo code here.